
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialProgramming
4.7 Rating 65 Questions 60 mins read17843 Readers

Spring Security is a powerful and highly customizable authentication and access-control framework for Java applications. It provides a flexible and expressive API for authenticating users, securing routes, and enforcing access policies.Spring Security is a powerful and highly customizable authentication and access-control framework for Java applications. It provides a flexible and expressive API for authenticating users, securing routes, and enforcing access policies.
Spring Security is based on a series of filters that are applied to incoming HTTP requests. Each filter performs a specific security task, such as authenticating the user, checking for authorization, or enforcing HTTPS. When a request is received, it is passed through the chain of filters, and the appropriate action is taken based on the configuration of the filters.
Spring Security is highly configurable and can be easily integrated with other Spring projects and third-party authentication providers. It provides support for a wide range of authentication mechanisms, including basic authentication, form-based authentication, and OAuth. It also includes support for secure communication over SSL/TLS and for protecting against common web vulnerabilities such as cross-site scripting (XSS) and cross-site request forgery (CSRF).
Spring Security provides a number of features to support authentication and authorization in Spring applications:
Authentication: Spring Security supports a wide range of authentication mechanisms, including basic authentication, form-based authentication, and OAuth. It also provides support for integrating with external authentication systems such as LDAP, Kerberos, and SAML.
User Details Service: Spring Security provides a UserDetailsService interface that you can use to load user-specific data from a database or other source. This data can include the user's credentials, as well as any additional information required by your application, such as the user's roles and permissions.
Authorization: Spring Security provides a number of ways to enforce access control in your application. You can use method-level security to restrict access to specific methods or classes based on the user's roles or permissions. You can also use URL-based security to restrict access to specific URLs based on the user's roles or permissions.
SecurityContextHolder: Spring Security provides a SecurityContextHolder class that you can use to store the currently authenticated user and their details. This is useful when you need to access the user's details from anywhere in your application.
WebSecurityConfigurer: Spring Security provides a WebSecurityConfigurer interface that you can use to customize the security configuration for your application. This includes setting up authentication and authorization rules, as well as specifying which URLs should be secured and which should be publicly accessible.
Overall, Spring Security provides a comprehensive and flexible framework for securing your Spring applications and protecting them against common threats such as unauthorized access, cross-site scripting, and cross-site request forgery.
This is one of the most frequently asked Spring Security interview questions for freshers in recent times.
Spring Security supports a wide range of authentication methods. Here are a few common ones:
These are just a few examples of the many authentication methods supported by Spring Security.
Spring Security can be used to secure applications that use the OAuth2 authorization framework. OAuth2 is a framework that allows a user to grant a third-party application access to their resources without sharing their credentials (usually a username and password). Instead, the user is issued a token that the third-party application can use to access the user's resources.
Spring Security can be used to authenticate the user and issue the token. It can also be used to secure the resources that the token grants access to by requiring the token to be included in the request header when the resources are accessed.
Spring Security also provides support for integrating with OAuth2 provider servers, such as Facebook and Google. This allows users to authenticate using their third-party accounts and allows the application to access resources from the third-party servers on behalf of the user.
To integrate Spring Security with LDAP for authentication, you will need to configure the LdapAuthenticationProvider bean in your application's Spring Security configuration.
Here is an example of how to do this:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .ldapAuthentication() .userDnPatterns("uid={0},ou=people") .groupSearchBase("ou=groups") .contextSource() .url("ldap://localhost:8389/dc=springframework,dc=org") .and() .passwordCompare() .passwordEncoder(new LdapShaPasswordEncoder()) .passwordAttribute("userPassword"); }} Spring Security provides a number of features to secure RESTful web services. Some common approaches for securing RESTful web services with Spring Security include:
HTTP Basic Authentication: This is the simplest form of authentication where the client sends an HTTP header with a username and password in each request. The username and password are encoded in base64 and sent in the Authorization header.
Token-based Authentication: This is a more secure approach where the client sends an HTTP header with a token in each request. The token is generated by the server and sent to the client in the Authorization header. The server verifies the token in each request to authenticate the client.
OAuth2 Authentication: This is a more secure approach where the client uses the OAuth 2.0 protocol to authenticate with the server. The client obtains an access token from the authorization server and sends it in the Authorization header of each request to the resource server. The resource server verifies the token with the authorization server to authenticate the client.
To use these approaches with Spring Security, you will need to do the following:
1. Add the Spring Security dependencies to your project:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.4.1</version></dependency><dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.4.1</version></dependency>
2. Configure the security filter chain in your security configuration:
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) .and() .addFilter(new TokenAuthenticationFilter(authenticationManager())) .addFilter(new BasicAuthenticationFilter(authenticationManager())) .addFilter(new OAuth2AuthenticationFilter(authenticationManager())) .authorizeRequests() .anyRequest().authenticated(); }} 3. Implement the authentication filters:
public class TokenAuthenticationFilter extends GenericFilterBean { private final AuthenticationManager authenticationManager; public TokenAuthenticationFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String token = request.getParameter("token"); if (token == null) { chain.doFilter(request, response); return; } TokenAuthenticationToken authRequest = new TokenAuthenticationToken(token); Authentication authResult = authenticationManager.authenticate(authRequest); SecurityContextHolder.getContext().setAuthentication(authResult); chain.doFilter(request, response); }}public class BasicAuthenticationFilter extends BasicAuthenticationFilter { public BasicAuthenticationFilter(Authentication A must-know for anyone looking for top Spring Security interview questions, this is one of the frequently asked Spring Security advanced interview questions.
Spring Security provides a number of method security annotations that you can use to secure your application at the method level. These annotations can be used to define fine-grained security policies for your application.
Some common method security annotations in Spring Security are:
To use these annotations, you will need to do the following:
1. Add the Spring Security dependencies to your project:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.4.1</version></dependency><dependency> <groupspring frameworkamework.security</groupId <artifactId>spring-security-web</artifactId <version>5.4.1</version</dependency>
2. Enable method security in your security configuration:
@Configuration@EnableWebSecurity@EnableGlobalMethodSecurity(prePostEnabled = true)public class SecurityConfig extends WebSecurityConfigurerAdapter { // ...} 3. Use the method security annotations in your service methods:3.Use the method security annotations in your service methods:
@Servicepublic class UserService { @PreAuthorize("hasRole('ADMIN')") public void deleteUser(Long userId) { // Delete user } @PostAuthorize("hasPermission(returnObject, 'READ')") public User getUser(Long userId) { // Return user } @PreFilter("hasPermission(filterObject, 'WRITE')") public void updateUsers(List<User> users) { // Update users } @PostFilter("hasPermission(filterObject, 'READ')") public List<User> getUsers() { // Return list of users }} These annotations will be used by the Spring Security runtime to enforce the specified security policies on the annotated methods.
Spring Security provides expression-based access control to customize the authentication and authorization behavior in your application. With expression-based access control, you can use expressions to define security policies that are evaluated at runtime.
To use expression-based access control, you will need to do the following:
1. Add the Spring Security dependencies to your project:
<dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.4.1</version></dependency><dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.4.1</version></dependency>
2. Enable expression-based access control in your security configuration:
@Configuration@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .expressionHandler(expressionHandler()) .antMatchers("/admin/**").access("hasRole('ADMIN')") .antMatchers("/user/**").access("hasAnyRole('USER', 'ADMIN')") .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .defaultSuccessUrl("/home", true) .and() .logout() .invalidateHttpSession(true) .clearAuthentication(true) .deleteCookies("JSESSIONID") .logoutUrl("/logout") .logoutSuccessUrl("/login") .and() .csrf().disable(); } @Bean public DefaultWebSecurityExpressionHandler expressionHandler() { DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler(); handler.setRoleHierarchy(roleHierarchy()); return handler; } @Bean public RoleHierarchy roleHierarchy() { RoleHierarchyImpl hierarchy = new RoleHierarchyImpl(); hierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER"); return hierarchy; }} In the security configuration above, we have enabled expression-based access control and specified security policies for the /admin and /user paths using expressions. The expressions will be evaluated at runtime by the expressionHandler to determine whether the user has the required permissions to access the resources.
We have also specified a role hierarchy using the roleHierarchy bean. This will be used to determine the effective roles of the user at runtime.
You can also use expression-based access control with method security annotations, such as @PreAuthorize and @PostAuthorize, to secure your service methods.
@Servicepublic class UserService { @PreAuthorize("hasRole('ADMIN')") public void deleteUser(Long userId) { // Delete user } @PostAuthorize("hasPermission(returnObject, 'READ')") public User getUser(Long userId) Spring Security's remember-me feature allows a user to remain logged in even after their session has ended. This is achieved by sending a cookie to the user's browser and storing a token on the server. The next time the user visits the application, the cookie is sent back to the server, and the server looks up the corresponding token. If the token is found, the user is automatically logged in.
To enable the remember-me feature, you need to configure it in your application's Spring Security configuration. Here's an example of how to do this using a database as the persistent store:
@Configuration@EnableWebSecuritypublic class SecurityConfiguration extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Override protected void configure(HttpSecurity http) throws Exception { http .rememberMe() .key("uniqueAndSecret") .userDetailsService(userDetailsService()) .tokenRepository(persistentTokenRepository()) .tokenValiditySeconds(24 * 60 * 60); // valid for 1 day } @Bean public PersistentTokenRepository persistentTokenRepository() { JdbcTokenRepositoryImpl jdbcTokenRepositoryImpl = new JdbcTokenRepositoryImpl(); jdbcTokenRepositoryImpl.setDataSource(dataSource); return jdbcTokenRepositoryImpl; } @Bean public UserDetailsService userDetailsService() { // your user details service implementation }} In the example above, we are using a JdbcTokenRepositoryImpl, which stores the remember-me tokens in a database using JDBC. The key attribute is used to encrypt the remember-me cookie, and the tokenValiditySeconds attribute is used to specify the length of time for which the remember-me token is valid.
You will also need to create a table in your database to store the remember-me tokens. You can use the following SQL script to create the table:
CREATE TABLE persistent_logins ( username VARCHAR(64) NOT NULL, series VARCHAR(64) NOT NULL, token VARCHAR(64) NOT NULL, last_used TIMESTAMP NOT NULL, PRIMARY KEY (series));
One way to integrate Spring Security with a front-end framework like Angular or React is to use Spring Security's CSRF (Cross-Site Request Forgery) protection.
CSRF protection ensures that an attacker cannot send a forged request from a user's browser to your application. This is important because it helps to protect your application against certain types of attacks, such as cross-site scripting (XSS) attacks.
To enable CSRF protection in your Spring Security configuration, you can use the csrf() method:
@Overrideprotected void configure(HttpSecurity http) throws Exception { http .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .and() // other configuration} This will cause Spring Security to send a CSRF token to the client as a cookie and to expect the token to be included in the header of all authenticated requests.
To integrate this with a front-end framework like Angular or React, you will need to send the CSRF token with each authenticated request. In Angular, you can do this by adding an HTTP interceptor to add the token to the header of each request:
import { Injectable } from '@angular/core';import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';import { CookieService } from 'ngx-cookie-service';@Injectable()export class CsrfInterceptor implements HttpInterceptor { constructor(private cookieService: CookieService) {} intercept(request: HttpRequest<any>, next: HttpHandler) { const csrfToken = this.cookieService.get('XSRF-TOKEN'); if (csrfToken) { request = request.clone({ setHeaders: { 'X-XSRF-TOKEN': csrfToken } }); } return next.handle(request); }} And in React, you can use the getCookie function from the js-cookie library to get the CSRF token and include it in the header of each authenticated request:
import axios from 'axios';import Cookies from 'js-cookie';const csrfToken = Cookies.get('XSRF-TOKEN');const instance = axios.create({ headers: { 'X-XSRF-TOKEN': csrfToken }});export default instance; Spring Security can handle session management in several ways. One way is by using cookies to maintain a session. When a user logs in, Spring Security creates a session for the user and sends a cookie to the user's browser containing a session identifier. When the user makes subsequent requests to the server, the browser includes the cookie, allowing Spring Security to associate the request with the user's session.
Spring Security can also maintain a session by storing the session identifier in a database and associating it with the user's session data. In this case, the session identifier is not stored in a cookie but is instead included in the URL as a request parameter or is passed as a request header.
Another option is to use an HTTP header or a custom request parameter to transport the session identifier.
You can customize the way that Spring Security handles session management by setting the <session-management> element in your application's configuration.
A staple in Spring Security technical interview questions, be prepared to answer this one using your hands-on experience.
In the context of Spring Security, authentication is the process of verifying the identity of a user or client. This typically involves verifying a username and password combination, but it can also involve other methods, such as two-factor authentication or certificate-based authentication.
Authorization, on the other hand, is the process of granting or denying access to a user or client based on their authenticated identity and the permissions or roles associated with that identity. For example, once a user is authenticated, they may be authorized to perform certain actions or access certain resources based on their role within the system (e.g., administrator, user, etc.).
Spring Security provides a number of features to help with both authentication and authorization, including support for a wide range of authentication methods, the ability to define custom authorization rules, and integration with external authorization systems.
Spring Security can be integrated with OAuth2 in several ways to provide authorization for your application.
One way to integrate with OAuth2 is by using the spring-security-oauth2 module, which provides support for both OAuth1 and OAuth2. With this approach, you can use Spring Security to authenticate the user and then use the OAuth2Authentication class to authorize the user based on the permissions granted by the OAuth2 authorization server.
Another option is to use the spring-security-oauth2-client module, which provides support for integrating with an OAuth2 authorization server as an OAuth2 client. This allows your application to obtain access tokens from the authorization server and use those tokens to authenticate requests to protected resources.
You can also use the spring-security-oauth2-resource-server module to configure your application as an OAuth2 resource server, which means that it can accept and validate access tokens from an OAuth2 authorization server and use those tokens to authenticate requests.
Regardless of which approach you to choose, you will need to configure your application with the necessary information about the OAuth2 authorization server, such as the authorization and token endpoint URLs and the client credentials. This can typically be done using properties in your application's configuration.Regardless of which approach you choose, you will need to configure your application with the necessary information about the OAuth2 authorization server, such as the authorization and token endpoint URLs and the client credentials. This can typically be done using properties in your application's configuration.
Cross-site request forgery is a web security vulnerability in which users are tricked into performing some actions without their knowledge. CSRF attacks happen because the requests comings from valid websites and the requests coming from malicious websites are the same and cannot be rejected. Spring provides two mechanisms to help against CSRF attacks.
Synchronizer token pattern :
In this solution, each HTTP request is expected to contain a secure, randomly generated token called a CSRF token. When an HTTP request is received, the server must compare the expected CSRF token against the actual CSRF token and reject the request in case of a mismatch. This can only work when the CSRF token is expected to be part of the HTTP request and not part of cookies since cookies can be exploited by the malicious website.
Same site attribute :
In this solution, the expectation is to set SameSite attribute by the server in the cookie. Setting this attribute will result in the cookie not being sent from websites other than the original website.
To secure a REST API using Spring Security, you can follow these steps:
Add the Spring Security dependency to your project.
Configure Spring Security in your application by adding a WebSecurityConfigurerAdapter and overriding the configure(HttpSecurity http) method.
In the configure method, specify the URL patterns that you want to secure and the authentication and authorization rules for those patterns. For example, you might use http.antMatcher("/api/**").authorizeRequests().anyRequest().authenticated() to require authentication for all requests to the /api endpoint.
Configure an authentication manager and specify the authentication provider(s) that you want to use. For example, you might use http.authenticationProvider(authenticationProvider()) to use a custom authentication provider.
(Optional) If you want to use JSON Web Tokens (JWTs) to authenticate your API, you can use the spring-security-jwt library to create and verify JWTs.
Here is an example configuration that secures a REST API using Spring Security:
Copy code
@EnableWebSecuritypublic class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .cors().and() .csrf().disable() .antMatcher("/api/**") .authorizeRequests() .anyRequest().authenticated() .and() .addFilter(new JwtAuthenticationFilter(authenticationManager())) .addFilter(new JwtAuthorizationFilter(authenticationManager(), this.userRepository)) .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public DaoAuthenticationProvider authenticationProvider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(); provider.setPasswordEncoder(passwordEncoder()); provider.setUserDetailsService(this.userDetailsService); return provider; }} This configuration enables Spring Security and disables CSRF protection and session management. It also defines a custom authentication filter that uses JWTs to authenticate requests.