Spring Security Interview Questions and Answers

 Ace your Java interviews with this comprehensive guide on Spring Security interview questions. Covers authentication, authorization, JWT, OAuth2, roles, and best practices for Spring Security 6.

1. What is Spring Security?

Spring Security is a powerful, customizable authentication and authorization framework that protects Java applications. It handles security concerns such as user authentication, role-based access control, session management, and protection against common security threats.

Spring Security integrates seamlessly with Spring Boot, allowing developers to quickly secure REST APIs and web applications.

2. What are the core components of Spring Security?

Core components include:

  • Principal: Currently logged in user.
  • Authentication: Represents user identity
  • Authorization: Access control management
  • GrantedAuthority: Permission granted to the principal.
  • AuthenticationManager: Controller in the authentication process. Authenticates the user saved in memory via authenticate().
  • AuthenticationProvider: Interface that maps to a data store that stores your data.
  • UserDetails: Data object that contains the user credentials but also the role of that user.
  • UserDetailsService: Loads user-specific data
  • SecurityContext: Holds the authentication object
  • PasswordEncoder: Encodes and verifies passwords
  • SecurityFilterChain: Handles security filters

These components form the foundation of Spring Security.

The Spring Security Architecture

3. Explain Authentication vs. Authorization in Spring Security.

  • Authentication verifies the identity of the user (e.g., username/password).
  • Authorization checks whether the authenticated user has permission to access specific resources.

Authentication precedes authorization in any security flow.

4. How do you configure security in Spring Security 6?

Spring Security 6 recommends configuring security via SecurityFilterChain instead of extending WebSecurityConfigurerAdapter (deprecated).

Example:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.formLogin(withDefaults())
.httpBasic(withDefaults())
.build();
}

The default configuration (shown in the preceding example):

  • Ensures that any request to our application requires the user to be authenticated
  • Let users authenticate with form-based login
  • Let users authenticate with HTTP Basic authentication

5. What is a SecurityContext?

SecurityContext stores authentication details of the currently authenticated user. It contains an Authentication object which represents the user's identity, roles, and credentials.

Spring Security uses SecurityContextHolder to access this context globally within an application.

6. What is UserDetailsService?

UserDetailsService is an interface that loads user-specific data during authentication. It provides a method loadUserByUsername(String username) that returns user details, including username, password, and granted authorities (roles).

Here is the code snippet to create a CustomUserDetailsService class that implements the UserDetailsService interface ( Spring security in-built interface) and provides an implementation for the loadUserByUername() method:

import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

private UserRepository userRepository;

@Override
public UserDetails loadUserByUsername(String usernameOrEmail) throws UsernameNotFoundException {

User user = userRepository.findByUsernameOrEmail(usernameOrEmail, usernameOrEmail)
.orElseThrow(() -> new UsernameNotFoundException("User not exists by Username or Email"));

Set<GrantedAuthority> authorities = user.getRoles().stream()
.map((role) -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toSet());

return new org.springframework.security.core.userdetails.User(
usernameOrEmail,
user.getPassword(),
authorities
);
}
}

7. Explain PasswordEncoder and its importance.

PasswordEncoder is used for hashing passwords before storing them. It ensures that passwords are never stored in plaintext. Popular implementations include:

  • BCryptPasswordEncoder (recommended)
  • Argon2PasswordEncoder

Example:

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

8. What is JWT and how is it used in Spring Security?

JWT (JSON Web Token) is a compact, URL-safe token used for securely transmitting information between parties. It contains claims like user identity and roles, and it’s digitally signed to ensure integrity.

In Spring Security, JWT is commonly used for stateless authentication. After a user logs in, the server generates a JWT and sends it to the client. For each subsequent request, the client sends the JWT in the Authorization header. Spring Security then validates the token to authenticate the user without needing session storage on the server.

9. How do you implement JWT with Spring Security?

To implement JWT with Spring Security, you typically follow these steps:

  1. Authenticate User: Create a login endpoint where the user submits credentials.
  2. Generate JWT: If authentication is successful, generate a JWT and return it to the client.
  3. Configure Filters: Create a custom JWT filter to intercept incoming requests and validate the token.
  4. Add Filter to Security Config: Register the JWT filter in the Spring Security configuration before the UsernamePasswordAuthenticationFilter.
  5. Secure Endpoints: Use annotations or security config to protect routes based on roles/authorities in the JWT.

This allows stateless, token-based authentication without using server-side sessions.

Check out the complete example:

10. What is OAuth2 in Spring Security?

OAuth2 in Spring Security is a framework that provides secure delegated access using tokens. It allows applications to authenticate and authorize users via third-party providers (like Google, Facebook, etc.) without handling user credentials directly.

Spring Security supports OAuth2 for both login (authorization code flow) and resource server scenarios, enabling secure API access using access tokens issued by an OAuth2 provider.

OAuth2 enables Single Sign-On (SSO) and third-party authentication.

11. What are the authorities and roles in Spring Security?

  • Authority: Specific permission granted to a user (e.g., ROLE_ADMIN).
  • Role: Special type of authority prefixed by “ROLE_” and represents higher-level access.

Spring Security uses roles extensively for role-based authorization.

12. Explain method-level security.

Method-level security in Spring Security allows you to control access to individual methods using annotations. It ensures that only authorized users can execute specific service or controller methods.

Common annotations include:

  • @PreAuthorize – Checks permissions before method execution.
  • @PostAuthorize – Checks permissions after method execution.
  • @Secured – Specifies required roles.
  • @RolesAllowed – Similar to @Secured, often used with JSR-250.

This approach adds fine-grained security directly at the business logic level.

Example:

@PreAuthorize("hasRole('ADMIN')")
public void adminMethod() {}

13. What is CSRF protection?

Cross-Site Request Forgery (CSRF) protection prevents unauthorized commands from authenticated users. Spring Security has built-in CSRF protection enabled by default.

You can disable it selectively:

http.csrf(csrf -> csrf.disable());

14. What is CORS and how do you configure it in Spring Security?

Cross-Origin Resource Sharing (CORS) controls access to resources across different origins (domains). Configure using Spring Security:

http.cors(cors -> cors.configurationSource(request -> {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("https://domain.com"));
config.setAllowedMethods(Arrays.asList("GET", "POST"));
return config;
}));

15. Explain Spring Security filters.

Spring Security filters are part of the security filter chain that processes incoming HTTP requests. Each filter has a specific responsibility, such as authentication, authorization, or CSRF protection.

Key filters include:

  • UsernamePasswordAuthenticationFilter – Handles login requests.
  • BasicAuthenticationFilter – Processes HTTP Basic auth.
  • JwtAuthenticationFilter – (custom) Validates JWT tokens.
  • SecurityContextPersistenceFilter – Manages the security context for each request.

Filters work together to apply security checks before the request reaches the controller. You can also add custom filters for additional processing.

Filters can be customized or extended as needed.

16. How do you customize login/logout behavior?

To customize login/logout behavior in Spring Security, you can configure it in your SecurityFilterChain or WebSecurityConfigurerAdapter (for older versions):

  • Login: Use .formLogin() to set custom login page, success/failure URLs, and handlers.
  • Logout: Use .logout() to define logout URL, success URL, and logout handlers.

Example:

http.formLogin()
.loginPage("/custom-login")
.defaultSuccessUrl("/dashboard")
.failureUrl("/login?error");

http.logout()
.logoutUrl("/perform-logout")
.logoutSuccessUrl("/login?logout");

This allows full control over the authentication flow.

17. What is session fixation protection?

Session fixation protection prevents attackers from exploiting sessions by assigning new session IDs upon login. Spring Security provides it by default.

18. What is Remember-Me authentication?

“Remember-Me” allows users to remain authenticated across browser sessions. Configure in Spring Security:

http.rememberMe(remember -> remember
.key("unique-key")
.tokenValiditySeconds(86400));

19. How does Spring Security handle concurrent logins?

Use sessionManagement() to limit concurrent logins:

http.sessionManagement(session -> session
.maximumSessions(1)
.expiredUrl("/login?expired"));

20. Explain role hierarchy in Spring Security.

Role hierarchy simplifies permission structures by defining higher-level roles that inherit lower-level roles:

@Bean
public RoleHierarchy roleHierarchy() {
RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
hierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");
return hierarchy;
}

21. What is ACL in Spring Security?

Access Control Lists (ACL) offer fine-grained permissions on domain objects. ACL specifies which users or roles have permissions for specific resources.

22. What is reactive security in Spring Security?

Reactive security supports non-blocking applications built using WebFlux. Configure with SecurityWebFilterChain:

@Bean
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
return http
.authorizeExchange(exchanges -> exchanges.anyExchange().authenticated())
.httpBasic(withDefaults())
.build();
}

23. How do you test Spring Security?

Use @WithMockUser and @WebMvcTest:

@WebMvcTest
@WithMockUser(roles="ADMIN")
public void testAdminAccess() {}

24. What is LDAP authentication?

LDAP authentication in Spring Security is a way to authenticate users against an LDAP (Lightweight Directory Access Protocol) server, such as Active Directory.

Spring Security connects to the LDAP server, verifies the user’s credentials, and optionally loads user roles and attributes from the directory.

It’s commonly used in enterprise environments to centralize user management and support single sign-on across applications.

25. How do you secure REST APIs?

Use JWT or OAuth2 for stateless authentication, enforce HTTPS, validate inputs, and apply RBAC (role-based access control).

To secure REST APIs in Spring Security, you typically:

  1. Disable form login and CSRF (for stateless APIs).
  2. Use token-based authentication (e.g., JWT) to validate users.
  3. Protect endpoints with role-based access using annotations like @PreAuthorize or hasRole().
  4. Configure CORS if APIs are accessed from different origins.
  5. Enable HTTPS to encrypt data in transit.

This setup ensures that only authorized users can access specific API resources securely.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare