Working of Spring Security


Working of Spring Security Interview with follow-up questions

1. Can you explain the basic workflow of Spring Security?

Spring Security works as a chain of servlet filters (the FilterChainProxy/SecurityFilterChain) that every request passes through before reaching your controller. The workflow:

  1. Filter chain intercepts the request (registered as one DelegatingFilterProxy, springSecurityFilterChain).
  2. Authentication — an authentication filter extracts credentials (form, Basic, Bearer token) and asks the AuthenticationManagerAuthenticationProviderUserDetailsService + PasswordEncoder to verify them.
  3. SecurityContext — on success, the resulting Authentication (principal + authorities) is stored in the SecurityContext (and persisted via the SecurityContextRepository).
  4. Authorization — the AuthorizationFilter checks the request against the access rules (authorizeHttpRequests) and method security (@PreAuthorize).
  5. Access granted → the request proceeds to the controller; denied → exception handling kicks in.
  6. Exception handling — the ExceptionTranslationFilter routes failures to an AuthenticationEntryPoint (401 / redirect to login) or AccessDeniedHandler (403).
Request → SecurityFilterChain → [authenticate] → SecurityContext
        → [authorize] → Controller   (or → 401/403)

The framing interviewers want: it's filter-based and ordered, authentication precedes authorization, and the SecurityContext carries identity through the request. The current note: you configure this chain via a SecurityFilterChain bean with the lambda DSL — the WebSecurityConfigurerAdapter approach was removed in Security 6.

↑ Back to top

Follow-up 1

How does Spring Security handle authentication?

Spring Security provides multiple ways to handle authentication:

  1. Form-based Authentication: This is the most common method where users provide their username and password in a login form. Spring Security handles the form submission, validates the credentials, and creates an authenticated session for the user.

  2. Basic Authentication: In this method, the user's credentials are sent with every request in the form of a username and password. Spring Security intercepts the request, validates the credentials, and creates an authenticated session.

  3. Token-based Authentication: This method involves the use of tokens, such as JSON Web Tokens (JWT), for authentication. The client sends the token with each request, and Spring Security validates the token to authenticate the user.

  4. External Authentication Providers: Spring Security can integrate with external authentication providers such as LDAP, OAuth, or SAML to authenticate users.

These authentication methods can be configured and customized based on the specific requirements of your application.

Follow-up 2

What is the role of SecurityContextHolder in Spring Security?

In Spring Security, the SecurityContextHolder is a central component that holds the security context of the current user. It provides access to the currently authenticated user and other security-related information. The SecurityContextHolder is implemented as a ThreadLocal, which means that each thread has its own instance of the SecurityContextHolder.

The SecurityContextHolder can be used to:

  1. Get the currently authenticated user: You can retrieve the currently authenticated user from the SecurityContextHolder using the SecurityContextHolder.getContext().getAuthentication() method.

  2. Set the security context: You can set the security context for the current thread using the SecurityContextHolder.getContext().setAuthentication(authentication) method. This is typically done after a successful authentication process.

  3. Clear the security context: You can clear the security context using the SecurityContextHolder.clearContext() method. This is typically done when the user logs out or the session expires.

The SecurityContextHolder is an important component in Spring Security as it allows you to access and manipulate the security context throughout your application.

Follow-up 3

Can you explain the concept of Authentication and Principal in Spring Security?

In Spring Security, authentication is the process of verifying the identity of a user. It involves validating the user's credentials, such as username and password, and creating an authenticated session for the user. Spring Security provides various mechanisms for authentication, including form-based authentication, basic authentication, token-based authentication, and integration with external authentication providers.

Once a user is authenticated, Spring Security creates a Principal object to represent the authenticated user. The Principal object contains information about the user, such as the username, authorities (roles and permissions), and other details. The Principal object can be accessed from the SecurityContextHolder using the SecurityContextHolder.getContext().getAuthentication().getPrincipal() method.

The Principal object can be used to perform authorization checks and retrieve user-specific information throughout the application. It is important to note that the Principal object is not limited to a specific type and can be customized based on the requirements of your application.

Follow-up 4

How does Spring Security handle authorization after authentication?

After a user is authenticated, Spring Security handles authorization by checking if the user has the necessary permissions to access the requested resources. Spring Security provides a flexible and customizable authorization mechanism based on roles and permissions.

  1. Role-based Authorization: Spring Security allows you to define roles for users and assign these roles to different resources. You can use annotations such as @PreAuthorize or @Secured to specify the required roles for a particular method or endpoint. Spring Security will automatically check if the authenticated user has the required roles before allowing access.

  2. Permission-based Authorization: In addition to roles, Spring Security also supports fine-grained permission-based authorization. You can define permissions for individual resources and assign these permissions to users or roles. You can use expressions such as hasPermission() or hasAuthority() to check if the authenticated user has the required permissions.

  3. Custom Authorization: Spring Security allows you to implement custom authorization logic by extending the AccessDecisionVoter interface or using custom expressions. This gives you full control over the authorization process and allows you to implement complex authorization rules.

By default, Spring Security provides a set of pre-defined roles and permissions, but you can customize and extend these as per your application's requirements.

2. How does Spring Security integrate with Spring MVC?

Spring Security integrates with Spring MVC at multiple layers, mostly automatically in Spring Boot:

  • Filter chain in front of the DispatcherServlet — the springSecurityFilterChain runs before MVC, so authentication/authorization happen before a request reaches a controller.
  • URL-level rulesauthorizeHttpRequests maps request matchers (which align with your MVC routes) to access rules.
  • Method security@PreAuthorize/@PostAuthorize on controller or service methods (@EnableMethodSecurity).
  • Argument resolvers — inject the current user into handler methods with @AuthenticationPrincipal or a Principal/Authentication parameter; access it in views via the security tag library/Thymeleaf-extras.
  • CSRF + headers — automatically wired into MVC forms and responses.
@GetMapping("/me")
String me(@AuthenticationPrincipal UserDetails user) { return user.getUsername(); }

The 2026 framing: with spring-boot-starter-security, all of this is auto-configured — adding the dependency secures the app by default; you customize via a SecurityFilterChain bean (no XML, no WebSecurityConfigurerAdapter). For REST APIs you typically pair it with oauth2ResourceServer().jwt() and stateless sessions, while server-rendered MVC apps use form login + CSRF. Exception handling integrates too: auth/access failures are translated to 401/403 (or redirects) before MVC's own exception handling.

↑ Back to top

Follow-up 1

What is the role of Spring Security in form login?

Spring Security provides built-in support for form-based login. When a user tries to access a secured resource without being authenticated, Spring Security intercepts the request and redirects the user to a login page. After successful authentication, the user is redirected back to the original requested resource. Spring Security handles the entire authentication process, including validating the user credentials, managing the authentication session, and redirecting the user to appropriate pages.

Follow-up 2

How does Spring Security handle CSRF protection?

Spring Security provides built-in support for CSRF (Cross-Site Request Forgery) protection. CSRF attacks occur when an attacker tricks a user's browser into making a malicious request on behalf of the user. To prevent this, Spring Security generates a CSRF token and includes it in forms or AJAX requests. When a form is submitted or an AJAX request is made, Spring Security checks the CSRF token to ensure that the request is legitimate. If the CSRF token is missing or invalid, the request is rejected.

Follow-up 3

How can we customize the login page in Spring Security?

To customize the login page in Spring Security, you can create a custom login page and configure Spring Security to use it. First, create a JSP, Thymeleaf template, or any other view technology file for the custom login page. Then, configure Spring Security to use this custom login page by specifying the login page URL in the security configuration. You can also customize the login form fields, error messages, and other aspects of the login page by modifying the custom login page file.

3. What is the role of filters in Spring Security?

Filters are the fundamental building block of Spring Security — it's implemented as an ordered chain of servlet filters (a SecurityFilterChain behind the FilterChainProxy) that each handle one concern of request processing before the request reaches your controller.

Important filters, roughly in order:

  • SecurityContextHolderFilter — loads any existing SecurityContext for the request.
  • CsrfFilter — validates the CSRF token on state-changing requests.
  • Authentication filtersUsernamePasswordAuthenticationFilter, BasicAuthenticationFilter, the Bearer-token/OAuth2 filters.
  • ExceptionTranslationFilter — converts auth/access exceptions into 401 (AuthenticationEntryPoint) / 403 (AccessDeniedHandler).
  • AuthorizationFilter — enforces the access rules (the last gate before the app).
request → [context] → [csrf] → [authn filters] → [exception translation]
        → [authorization] → DispatcherServlet/controller

Points interviewers reward: order matters (authentication before authorization), each filter has a single responsibility, and you can add a custom filter at a specific position via http.addFilterBefore/After(...) — e.g. a JWT-validation filter. In Spring Security 6 the chain is built from a SecurityFilterChain bean, and you can register multiple chains matched by securityMatcher (e.g. one for /api/**, another for the UI). Understanding that "Spring Security is a filter chain" is the heart of this question.

↑ Back to top

Follow-up 1

Can you explain the concept of FilterChain in Spring Security?

In Spring Security, the FilterChain is a series of filters that are applied to incoming requests. Each filter in the chain performs a specific security-related task. The FilterChain is responsible for passing the request through each filter in the correct order. Once the request passes through all the filters in the chain, it reaches the application's controllers for further processing.

Follow-up 2

How can we add custom filters in Spring Security?

To add custom filters in Spring Security, you need to create a class that implements the javax.servlet.Filter interface. This class should contain the logic for your custom filter. Then, you can configure the custom filter in the Spring Security filter chain by extending the WebSecurityConfigurerAdapter class and overriding the configure(HttpSecurity http) method. Inside this method, you can use the addFilterBefore() or addFilterAfter() methods to add your custom filter at a specific position in the filter chain.

Follow-up 3

What is the order of filters in Spring Security and why is it important?

The order of filters in Spring Security is important because each filter has a specific purpose and may depend on the output of previous filters. By default, Spring Security applies the filters in the following order:

  1. ChannelProcessingFilter
  2. SecurityContextPersistenceFilter
  3. ConcurrentSessionFilter
  4. LogoutFilter
  5. UsernamePasswordAuthenticationFilter
  6. RequestCacheAwareFilter
  7. SecurityContextHolderAwareRequestFilter
  8. AnonymousAuthenticationFilter
  9. SessionManagementFilter
  10. ExceptionTranslationFilter
  11. FilterSecurityInterceptor

However, you can customize the order of filters by extending the WebSecurityConfigurerAdapter class and overriding the configure(HttpSecurity http) method. Inside this method, you can use the addFilterBefore() or addFilterAfter() methods to specify the position of each filter in the filter chain.

4. How can we handle exception handling in Spring Security?

Spring Security separates two failure cases, each with its own hook, handled by the ExceptionTranslationFilter:

  • Authentication failure / not authenticatedAuthenticationEntryPoint.commence() — e.g. redirect to login (web app) or return 401 with a WWW-Authenticate header (API).
  • Authenticated but not permittedAccessDeniedHandler.handle() — return 403 Forbidden.
http.exceptionHandling(ex -> ex
    .authenticationEntryPoint((req, res, e) ->
        res.sendError(HttpStatus.UNAUTHORIZED.value()))
    .accessDeniedHandler((req, res, e) ->
        res.sendError(HttpStatus.FORBIDDEN.value())));

Additional approaches interviewers like: for REST APIs, customize these to emit consistent JSON (e.g. RFC 9457 ProblemDetail); for OAuth2 resource servers, configure the entry point/handler on oauth2ResourceServer. Note that exceptions thrown inside controllers are handled by MVC's @ControllerAdvice, but security exceptions thrown in the filter chain (before MVC) are handled here — a common point of confusion. Also, AuthenticationFailureHandler/AuthenticationSuccessHandler customize form-login outcomes.

The clean summary: implement a custom AuthenticationEntryPoint (401) and AccessDeniedHandler (403) — and remember it's 401 for "who are you?" vs 403 for "you can't do that."

↑ Back to top

Follow-up 1

What is the role of AccessDeniedHandler in Spring Security?

The AccessDeniedHandler interface in Spring Security is responsible for handling access denied exceptions. It has a single method handle() which is called when an access denied exception occurs. The default implementation of AccessDeniedHandler in Spring Security is AccessDeniedHandlerImpl, which sends a 403 Forbidden response to the client.

Follow-up 2

How can we customize AccessDeniedHandler?

To customize the AccessDeniedHandler in Spring Security, we can create a custom implementation of the AccessDeniedHandler interface. This custom implementation can be configured in the Spring Security configuration file using the accessDeniedHandler() method. For example:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .exceptionHandling()
                .accessDeniedHandler(customAccessDeniedHandler());
    }

    @Bean
    public AccessDeniedHandler customAccessDeniedHandler() {
        return new CustomAccessDeniedHandler();
    }

}

Follow-up 3

How does Spring Security handle session management?

Spring Security provides various mechanisms for session management. Some of the common features include:

  1. Session fixation protection: Spring Security automatically protects against session fixation attacks by changing the session identifier after successful authentication.

  2. Concurrent session control: Spring Security allows controlling the maximum number of concurrent sessions per user. When the maximum number of sessions is reached, the user can be prevented from logging in or an existing session can be expired.

  3. Session timeout: Spring Security allows configuring the session timeout duration. When the session timeout is reached, the user can be automatically logged out.

  4. Session creation policy: Spring Security allows configuring the session creation policy, which determines when a new session should be created. The options include always, ifRequired, never, and stateless.

These session management features can be configured in the Spring Security configuration file.

5. Can you explain the concept of OAuth2 in Spring Security?

OAuth2 is the delegated authorization framework (and OIDC layers authentication on top of it). Spring Security has first-class, built-in OAuth2 support, split into three roles you should distinguish:

  • oauth2Login — your app is a client that lets users log in via Google/GitHub/Okta (OIDC); Spring handles the authorization-code flow and creates the session.
  • oauth2ResourceServer — your app is an API that validates incoming access tokens (JWT or opaque) on each request — the standard for securing stateless REST APIs.
  • oauth2Client — your app calls other OAuth2-protected APIs, with Spring managing tokens/refresh.
http.oauth2ResourceServer(oauth -> oauth.jwt(withDefaults()));  // validate JWTs
// or: http.oauth2Login(withDefaults());                        // social/OIDC login

The crucial 2026 correction: the old standalone "Spring Security OAuth2" project is deprecated/EOL — its functionality was merged into Spring Security core (the oauth2* DSL above). For building your own authorization server (issuing tokens), use the separate Spring Authorization Server project, not the legacy module. So a current answer names the built-in oauth2ResourceServer/oauth2Login/oauth2Client support and Spring Authorization Server — referencing spring-security-oauth is a sign of stale knowledge. Use the Authorization Code flow with PKCE for clients.

↑ Back to top

Follow-up 1

How does Spring Security handle OAuth2 authentication?

Spring Security provides several components to handle OAuth2 authentication. The AuthorizationServerConfigurer interface is used to configure the authorization server, which is responsible for issuing access tokens to clients. The ResourceServerConfigurer interface is used to configure the resource server, which is responsible for validating access tokens and protecting the resources. Spring Security also provides various grant types, such as authorization_code, password, client_credentials, and refresh_token, to support different authentication scenarios.

Follow-up 2

What is the role of TokenStore in OAuth2?

The TokenStore interface in Spring Security OAuth2 is responsible for storing and retrieving access tokens. It provides methods to store, read, and remove access tokens. Spring Security provides several implementations of the TokenStore interface, such as InMemoryTokenStore, JdbcTokenStore, and JwtTokenStore. The choice of TokenStore implementation depends on the specific requirements of the application, such as scalability, persistence, and token format.

Follow-up 3

How can we implement OAuth2 with Spring Security?

To implement OAuth2 with Spring Security, you need to add the Spring Security OAuth2 dependency to your project. Then, you can configure the OAuth2 components using Java configuration or XML configuration. You need to define an AuthorizationServerConfigurer bean to configure the authorization server and an ResourceServerConfigurer bean to configure the resource server. You also need to configure the TokenStore implementation to store and retrieve access tokens. Finally, you can secure your endpoints by applying appropriate security rules using annotations or configuration.

Live mock interview

Mock interview: Working of Spring Security

Intermediate ~5 min Your own free AI key

Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.