Spring Security is a flexible, extensible security framework for Java applications built on the Spring Framework. Its core concerns are authentication (verifying identity) and authorization (determining permitted actions). This guide covers key topics including configuration, securing REST APIs, method-level security, OAuth2/JWT integration, and more.
1. What is Spring Security?
Spring Security is a Java framework that provides authentication, authorization and access-control services for Spring-based applications. It integrates with other Spring modules to protect resources and ensure that users are permitted to perform actions.
2. What are the key features of Spring Security?
Some of the core features of Spring Security are depicted below:
- Authentication: verifying user identity.
- Authorization: deciding whether a user is allowed to perform an action.
- Principal: the representation of the currently logged-in user.
- GrantedAuthority: a representation of a user’s rights or permissions.
- Protection against common web threats such as CSRF and session fixation.
3. Difference between Authentication and Authorization in Spring Security.
Features | Authentication | Authorization |
|---|---|---|
Definition | Verifies user identity | Determines if an authenticated user can do a task |
Working | Checks credentials like username/password | Uses user identity and access-rules |
Result | Produces an authenticated token for the user | Grants or denies access to resources |
Know more about Authentication and Authorization in Spring Security
4. How to configure Authentication in Spring Security?
Steps to configure authentication:
- Extend WebSecurityConfigurerAdapter in a custom configuration class.
- Annotate the class with @EnableWebSecurity.
- Override configure(AuthenticationManagerBuilder) method.
- Define user credentials and roles.
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
5. How to configure Authorization in Spring Security?
Steps to configure authorization:
- Extend WebSecurityConfigurerAdapter.
- Override configure(HttpSecurity) method.
- Define access rules for specific URLs.
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/author/admin")
.hasRole("ADMIN")
.antMatchers("/author/user")
.hasRole("USER")
.antMatchers("/")
.permitAll()
.and()
.formLogin();
}
6. What is the Latest Version of Spring Security and What's New in It?
Latest version: Spring Security 6
New Features:
- Automatic .cors() enablement when CorsConfigurationSource bean is present.
- Simplified OAuth2 Client model configuration.
- Added OIDC Back-Channel Logout Support.
- Improved CVE-2023-34035 detection.
- Configurable RedirectStrategy and HTTP Basic request parsing.
7. Explain basic authentication in Spring Security.
Steps to implement Basic Authentication:
- Add dependency spring-boot-starter-security.
- Extend WebSecurityConfigurerAdapter.
- Override configure(HttpSecurity) method.
@EnableWebSecurity
public class MySecurityAppConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and().httpBasic();
}
}
Now, the application has basic authentication using the provided username and password.
Know more about Basic Authentication in Spring Security
8. How to Enable and Disable CSRF in Spring Security?
CSRF (Cross-Site Request Forgery) protection is enabled by default.
To disable it, modify the configuration class as shown below:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Value("${security.enable-csrf}")
private boolean csrfEnabled;
@Override
protected void configure(HttpSecurity http) throws Exception {
if (!csrfEnabled) {
http.csrf().disable();
}
}
}
Know more about: Spring Security – How to Enable and Disable CSRF
9. What is a Filter Chain in Spring Security?
Spring Security uses a chain of filters to apply security rules to requests. Each filter performs a specific function like authentication or authorization.
Request flow:
- Client sends request.
- Filters intercept the request in sequence.
- Security checks are applied before request reaches the controller.

Know more about Spring Security – Filter Chain with Example
10. When to Use Spring Security antMatcher()?
Used to configure URL-based access rules.
Supported patterns:
- ? → matches one character.
- * → matches zero or more characters.
- ** → matches zero or more directories.
Common methods:
- hasRole(), hasAnyRole(), hasAuthority(), authenticated(), anonymous()
Know more about Spring Security – Securing Endpoints Using antMatchers()
11. How to implement Spring Security in a simple Spring Boot application?
Add the dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Boot automatically secures endpoints with default authentication.
Know more about Simple Authentication in Spring Boot
12. How to configure Spring Security in Spring MVC application?
- Add spring-boot-starter-security in pom.xml.
- Extend WebSecurityConfigurerAdapter.
- Create a custom login page if required.
- Run the application, Spring Security manages authentication automatically.
13. How to Deny Access to All URLs in Spring Security?
Use denyAll() to block every request.
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeHttpRequests()
.anyRequest()
.denyAll()
.and()
.httpBasic();
}
Know more about Spring Security – Deny Access to All URLs
14. How to Get the Current Logged in User Details in Spring Security?
We can get the Current Logged in User Details in Spring Security with the help of the Principal and Authentication objects.
@GetMapping("/")
public String userDetails(Principal principal, Authentication auth, Model model) {
String userName = principal.getName();
Collection<? extends GrantedAuthority> roles = auth.getAuthorities();
model.addAttribute("username", userName);
model.addAttribute("roles", roles);
return "home";
}
Know more about Spring Security – Get the Current Logged in User Details
15. What is PasswordEncoder in Spring Security?
- Used to hash and verify passwords securely.
- Configured as a Spring bean.
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Common Encoders:
- BCryptPasswordEncoder
- Pbkdf2PasswordEncoder
- Argon2PasswordEncoder
- NoOpPasswordEncoder (for testing)
Know more about Spring Security - Password Encoder
16. What is @EnableWebSecurity Annotation?
- Enables Spring Security’s web security support.
- Works with @Configuration to register custom security configurations.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/hello").permitAll()
.anyRequest().authenticated()
.and().formLogin();
}
}
Spring Security Interview Questions for Intermediate
17. What is JWT in Spring Security?
JWT (JSON Web Token) is a secure way to transfer information between two parties as a JSON object. It is mainly used for authorization and information exchange.
A JWT consists of three parts separated by dots (.):
- Header: Contains algorithm and token type.
- Payload: Contains user data or claims.
- Signature: Verifies token integrity.
Example JWT:
NiIsInR5cCI6IkpXVCJ9. eyJzdWIiOiIibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ . SflKxwRJSMeKKF2QT4fwpMeJf36
Structure:

- NiIsInR5cCI6IkpXVCJ9: This is the header part and contains the algorithm and what type of token it is.
- eyJzdWIiOiIibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ: This is the data part (payload).
- SflKxwRJSMeKKF2QT4fwpMeJf36: This is the signature part. It is used to verify that the data or message does not change during the information transformation.
Use Case in Spring Security:
- JWT replaces session-based authentication.
- Each request carries the JWT in the Authorization header for validation.
To know more please refer to these articles:
18. What is OAuth and OAuth2 in Spring Security?
- OAuth is an open standard for authorization.
- OAuth2 is the most commonly used version of OAuth.
Key Points:
- Used for delegated access without sharing credentials.
- Allows third-party applications (like Google or Facebook) to access user data securely.
- Provides authorization, not authentication.
- Operates by issuing access tokens after user consent.
OAuth2 Components:

- Resource Owner: The user.
- Client Application: The app requesting access.
- Authorization Server: Issues access tokens.
- Resource Server: Hosts protected resources.
19. What is Keycloak and How to Integrate It with Spring Security?
- Keycloak is an open-source Identity and Access Management (IAM) tool by Red Hat.
- It provides features like user federation, single sign-on (SSO), and role-based access control.
Steps to Integrate with Spring Security:
1. Add the dependency:
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-spring-security-adapter</artifactId>
<version>21.1.2</version>
</dependency>
2. Configure Security Class:
@KeycloakConfiguration
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(keycloakAuthenticationProvider());
}
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests()
.antMatchers("/customers").hasRole("USER")
.antMatchers("/admin").hasRole("ADMIN")
.anyRequest().permitAll();
}
}
Advantages:
- Centralized user management.
- Built-in OAuth2 and OpenID Connect support.
- Easy integration with Spring Boot apps.
To know more please refer to these articles:
20. What is the role of an AuthenticationProvider in Spring Security?
- AuthenticationProvider performs the actual authentication logic.
- It validates credentials and returns an Authentication object upon success.
- Used internally by the AuthenticationManager.
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin")
.password("{noop}password")
.roles("USER");
}
Key Points:
- AuthenticationManager delegates to multiple AuthenticationProvider instances.
- ProviderManager is the most commonly used implementation.
Know more about Spring Security - Authentication Provider
21. How to Secure an Endpoint in Spring Security?
Step 1: Create a configuration class extending WebSecurityConfigurerAdapter.
Step 2: Override configure(HttpSecurity) and configure(AuthenticationManagerBuilder).
Step 3: Use annotations to secure endpoints.
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/secured").hasRole("USER")
.and().formLogin();
}
}
Enable Method Security:
@EnableGlobalMethodSecurity(securedEnabled = true)
public class MethodSecurityConfig {}
22. Explain UserDetailsService and UserDetails in Spring Security.
- UserDetailsService loads user-specific data for authentication.
- UserDetails holds user credentials and authorities.
Key Points:
- UserDetailsService has a single method:
UserDetails loadUserByUsername(String username);
- Returns an implementation of UserDetails containing: Username, Password, Authorities (Roles).
Example:
@Service
public class MyUserDetailsService implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) {
return new User("admin", "{noop}password", List.of(new SimpleGrantedAuthority("ROLE_ADMIN")));
}
}
Know more about Spring Security – UserDetailsService and UserDetails with Example
23. What is method-level security in Spring Security?
- grained access control at the method level.
- Achieved using annotations like @PreAuthorize and @PostAuthorize.Provides fine-
- Ensures that only authorized users can invoke certain methods.
Example Using @PreAuthorize:
@PreAuthorize("hasRole('ADMIN')")
public void deleteEmployee(Long id) {
// Only ADMIN can delete
}
Example Using @PostAuthorize:
@PostAuthorize("returnObject.owner == authentication.name")
public Employee getEmployeeDetails(Long id) {
// Accessible after execution check
}
To Enable Method Security:
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {}
Know more about Method-Level security in Spring Security
24. Difference between hasRole() and hasAuthority().
| Feature | hasRole() | hasAuthority() |
|---|---|---|
| Purpose | Used for checking roles | Used for checking authorities |
| Prefix Requirement | Automatically adds ROLE_ prefix | Requires full authority name |
| Syntax Example | .hasRole("ADMIN") | .hasAuthority("ROLE_ADMIN") |
| Use Case | When roles are prefixed automatically | When full authority name is used manually |
Interview Questions for Experienced
25. How does Spring Security handle Session Management?
- Prevents session fixation and concurrent login issues.
- Configured through HttpSecurity.sessionManagement().
Example:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
.maximumSessions(1)
.maxSessionsPreventsLogin(true);
}
SessionCreationPolicy options:
- ALWAYS: Creates session if needed.
- NEVER: Uses existing session only.
- STATELESS: No session (used in JWT).
- IF_REQUIRED: Default policy.
26. What is CSRF and how can it be handled in Spring Security?
- CSRF (Cross-Site Request Forgery) is an attack that tricks a user into performing unwanted actions.
- Spring Security enables CSRF protection by default.
Token-based protection:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
To disable (for stateless APIs):
http.csrf().disable();
Note: Never disable CSRF for browser-based applications.
27. How can you implement Two-Factor Authentication (2FA) in Spring Security?
2FA adds an extra layer of security using OTP or code verification.
Steps:
- Authenticate username + password.
- Generate a verification code (e.g., TOTP).
- Validate OTP in a separate endpoint before granting access.
Example (simplified flow):
@PostMapping("/verify-otp")
public ResponseEntity<String> verifyOtp(@RequestParam String code) {
if(otpService.validateCode(code))
return ResponseEntity.ok("2FA success");
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid OTP");
}
Libraries used:
- GoogleAuthenticator or Twilio for OTP delivery.
Know more about Two-Factor Authentication in Spring Security
28. Explain Hashing in Spring Security.
Hashing is the process of converting a plain-text password into an unreadable, fixed-length string using a one-way cryptographic function to ensure password security.
- Prevents storing plain-text passwords in the database.
- One-way process, cannot retrieve the original password.
- Protects credentials even if the database is compromised.
- Implemented in Spring Security using PasswordEncoder.
Common algorithms:
- Less Secure: MD5, SHA-1, SHA-256
- Recommended: BCrypt, PBKDF2, Argon2

Example:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
29. What are Security Expressions in Spring Security (SpEL)?
- Spring Expression Language (SpEL) enables dynamic access control logic.
- Common annotations: @PreAuthorize, @PostAuthorize, @PreFilter, @PostFilter.
Examples:
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
public void deleteEmployee(Long id) {}
@PostAuthorize("returnObject.owner == authentication.name")
public Employee getEmployee(Long id) { ... }
Custom Expressions:
- Create a custom PermissionEvaluator for business rules.
Know more about Spring Expression Language (SpEL)
30. How can you implement Role-Based Access Control (RBAC)?
Assign specific roles to users, and secure endpoints based on roles.
Example:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated();
}
Database tables:
- users, roles, user_roles for mapping.
31. Explain potential web application vulnerabilities and how Spring Security mitigates them?
Spring Security protects against common web application vulnerabilities like:
- SQL injection
- Cross Site Scripting (XSS)
- Cross Site Request Forgery (XSRF)
Spring Security mitigates them through filters and Content Security Policy.
32. How to implement Spring Security with in-memory user storage.
To implement Spring Security with in-memory user storage, follow the below steps:
Step 1: Add Starter dependency in XML file.
spring-boot-starter-security
Step 2: In Spring Security configuration, enable in-memory authentication.
auth.inMemoryAthentication()
Know more about Spring Security - In-Memory Authentication
33. How does Spring Security integrate with OAuth2 Resource Server?
Used when your app acts as a Resource Server verifying JWT access tokens issued by an Authorization Server.
Configuration:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.anyRequest().authenticated()
.and()
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
}
application.yml:
spring:
security:
oauth2:
resourceserver:
jwt:
issuer-uri: https://auth-server.com
34. How to customize Authentication Entry Point and Access Denied Handler?
AuthenticationEntryPoint: Handles unauthorized requests.
AccessDeniedHandler: Handles access denied after authentication.
Example:
@Component
public class CustomAuthEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized Access");
}
}
Configuration:
http.exceptionHandling()
.authenticationEntryPoint(customAuthEntryPoint)
.accessDeniedHandler(customAccessDeniedHandler);
35. Explain Salting and its usage.
- Salting is a process in Spring Security to combine random data with a password before password hashing.
- By increasing its uniqueness and complexity, it improves Hashing.
Note: Salting is automatically applied since Spring Security version 3.1.
36. How to disable Spring Security for specific endpoints?
- Useful for public resources or actuator endpoints.
Example:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/public/**", "/actuator/**").permitAll()
.anyRequest().authenticated();
}
Alternative: Exclude endpoints using WebSecurity
@Override
public void configure(WebSecurity web) {
web.ignoring().antMatchers("/css/**", "/js/**");
}