Spring Security Interview Questions and Answers

If you’re preparing for a job interview, these Spring security interview questions will help you understand key concepts and increase the confidence.

Spring-Security-logo

These Spring Security interview questions cover authentication, authorization, the servlet filter chain and common web-security scenarios. Each answer explains the responsibility of the component before discussing configuration. The answers keep configuration examples beside the behavior they demonstrate.

Core concepts

1. What does Spring Security provide?

Spring Security helps an application authenticate a caller, authorize a request and protect a servlet application against common web attacks. The application still defines its trusted users, access policy and data ownership rules.

request -> authentication: who is calling?
        -> authorization: may that identity do this?
        -> controller or denial response

Authentication may come from a form login, HTTP Basic or a bearer token. Authorization can be applied to request paths and service methods. For browser applications, Spring Security also supplies features such as CSRF protection and security response headers. Those protections need to be configured for the application’s actual client and deployment model.

2. Which components handle a servlet request?

The servlet container calls DelegatingFilterProxy, which delegates to Spring Security’s FilterChainProxy. FilterChainProxy chooses the first matching SecurityFilterChain. Filters in that chain can load a security context, protect the request, authenticate credentials and authorize access before the request reaches the servlet.

Servlet container
  -> DelegatingFilterProxy
  -> FilterChainProxy
  -> first matching SecurityFilterChain
  -> authentication filter -> AuthenticationManager -> AuthenticationProvider
  -> AuthorizationFilter -> controller or denial

An AuthenticationProvider checks a particular kind of credential. The result is an Authentication containing the principal and authorities. An AuthorizationManager uses that information and the configured policy to decide whether a protected operation may proceed. When multiple chains exist, order the specific request matchers before a catch-all chain.

Spring Security’s servlet architecture shows the filter roles and order in more detail.

3. What happens during form-login authentication?

When an unauthenticated browser requests a protected page, the configured authentication entry point can redirect it to a login page. On form submission, UsernamePasswordAuthenticationFilter reads the credentials and creates an unauthenticated Authentication request. AuthenticationManager delegates verification to a suitable provider.

POST /login
  -> UsernamePasswordAuthenticationFilter
  -> AuthenticationManager
  -> AuthenticationProvider checks user and password
  -> authenticated Authentication
  -> SecurityContext for later authorization

A typical username/password provider loads a UserDetails through UserDetailsService and checks the submitted password through PasswordEncoder. The authentication filter places the successful result in the SecurityContext. With session-based login, the context can be saved for later requests. A failed login follows the configured failure handler; an authenticated request still needs to pass authorization.

4. How does AuthenticationManager choose an AuthenticationProvider?

The usual ProviderManager asks its configured providers whether they support the incoming Authentication type. A supporting provider may authenticate it, return no result so another provider can try, or fail with an authentication exception. Provider order and the concrete providers matter.

Authentication request
  -> provider A supports type? no  -> skip
  -> provider B supports type? yes -> authenticate or continue
  -> successful Authentication, or authentication failure

For a username and password request, a configured DaoAuthenticationProvider can load the user and check the password using a PasswordEncoder. A JWT resource server uses a provider suited to JWT validation instead.

5. How does Spring Security authorize a request?

Authorization checks whether the current Authentication satisfies the rule for the request. The AuthorizationFilter uses an AuthorizationManager for this decision. Authentication and authorization are separate: knowing the user does not imply that the user may access /admin.

http.authorizeHttpRequests(authorize -> authorize
    .requestMatchers("/admin/**").hasRole("ADMIN")
    .anyRequest().authenticated());

An authenticated user without the required authority is denied. A request without an authenticated identity is sent through the configured authentication entry point. Method security can add another check when a service operation needs an ownership rule.

6. What does PasswordEncoder do, and which encoder should an application use?

A PasswordEncoder creates a stored representation of a password and later checks a raw password against it. An adaptive password hash is the usual choice for stored user passwords. Compare with matches; creating a second salted hash and comparing strings will not work reliably.

PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
String stored = encoder.encode("secret");
boolean valid = encoder.matches("secret", stored);

The factory returns a DelegatingPasswordEncoder. Its stored value includes an identifier such as {bcrypt}, so the matching encoder can be selected during verification. The application should choose a supported encoder and tune its work factor for its environment.

7. How to enable Spring security in a non-Spring boot application?

When it comes to enabling Spring Security in a non-Spring Boot application, there are a few approaches we can take. Let’s explore two standard methods:

  • Java-based configuration
  • XML-based configuration

Java-based Configuration With AbstractSecurityWebApplicationInitializer

In Java configuration, we can enable Spring Security by extending the AbstractSecurityWebApplicationInitializer class and optionally overriding its methods to configure the DelegatingFilterProxy and associate it with the springSecurityFilterChain bean. It avoids writing servlet-filter configurations in web.xml file.

We can define the custom security beans in the SecurityConfig.java.

public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {

   public SpringSecurityInitializer() {
       super(SecurityConfig.class);
   }
}

XML Based Configuration

In XML configuration, we need to explicitly define the DelegatingFilterProxy bean and map it to the springSecurityFilterChain bean using the filter name. This linkage is typically done in the web.xml file:

<filter>
  <filter-name>springSecurityFilterChain</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
  <filter-name>springSecurityFilterChain</filter-name>
  <url-pattern>/*</url-pattern>
  <dispatcher>ERROR</dispatcher>
  <dispatcher>REQUEST</dispatcher>
</filter-mapping>

8. How to enable Spring security in a Spring boot application?

Adding the security starter makes Boot’s security auto-configuration eligible. In a typical web application it supplies default security until an applicable custom configuration replaces it. Prefer explaining the resulting SecurityFilterChain and user configuration rather than relying on an old internal auto-configuration class name.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

9. What does @EnableWebSecurity enable?

@EnableWebSecurity activates Spring Security’s servlet web support and imports its configuration. In a Spring Boot web application, security auto-configuration commonly supplies this setup; an application can still define its own SecurityFilterChain bean for its access rules. The annotation alone is not a substitute for an explicit access policy.

@Configuration
@EnableWebSecurity
class SecurityConfig {
    @Bean
    SecurityFilterChain security(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(authorize -> authorize
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated())
            .formLogin(Customizer.withDefaults());
        return http.build();
    }
}

This chain allows the public path and requires authentication elsewhere. A separate user source or authentication provider determines which credentials are accepted.

10. How do roles differ from authorities?

An authority is a string granted to an authenticated principal. A role is a convention for an authority whose name has the configured role prefix, commonly ROLE_. Spring Security’s hasRole helper applies that prefix; hasAuthority checks the supplied authority string.

hasRole("ADMIN")       -> requires "ROLE_ADMIN" by default
hasAuthority("read")   -> requires "read" exactly

A role may represent a broad application responsibility, but Spring Security does not automatically expand it into a set of finer permissions. If an application wants that mapping, it must grant the corresponding authorities or define a policy that performs the mapping.

11. How do you protect a service method?

Enable method security and add an authorization annotation to a Spring-managed method. This is useful when an operation can be called from several entry points, or when the decision depends on method arguments rather than only the URL.

@Configuration
@EnableMethodSecurity
class MethodSecurityConfig {}

@Service
class ProductService {
    @PreAuthorize("hasRole('ADMIN')")
    void deleteProduct(Long productId) {
        // Delete the product after the authorization check.
    }
}

@EnableMethodSecurity enables pre/post annotations by default. Proxy-based method security applies when the call passes through the Spring proxy; a self-invocation inside the same bean does not pass through that proxy. The role check does not by itself prove that the caller owns a particular product.

12. How do you enable HTTP Basic authentication?

HTTP Basic sends a Base64-encoded username and password in the Authorization header on each request. Base64 does not protect the credentials, so use TLS. The server checks the credentials and then evaluates the request’s access rule.

@Bean
SecurityFilterChain basicSecurity(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(authorize -> authorize
            .anyRequest().authenticated())
        .httpBasic(Customizer.withDefaults());
    return http.build();
}

This configures the HTTP mechanism and requires an authenticated request. It still needs an appropriate user store or authentication provider.

13. How does Spring Security authenticate a JWT bearer token?

A JWT is a token format. A resource server extracts the bearer token from the request, validates its signature and required claims, and builds an Authentication for authorization. This does not require a custom JWT filter when the standard resource server support fits the application.

Authorization: Bearer <JWT>
    -> BearerTokenAuthenticationFilter
    -> JwtAuthenticationProvider / JwtDecoder
    -> authenticated principal and authorities
    -> endpoint authorization

With an issuer URL configured, Spring Security discovers the provider’s keys and validates the token’s issuer, expiry and not-before claims. Configure audience validation if the API requires a particular audience; do not assume every token for the issuer is intended for this API. For a working configuration, see the resource server answer below.

14. How does an application use OAuth 2.0 security?

First identify the application’s role. A client obtains an access token, an authorization server issues one, and a resource server accepts and validates it. A REST API that only protects endpoints is a resource server; it does not need to issue tokens.

client -> authorization server -> access token
client -> API resource server -> validate token -> authorize request

For a resource server that accepts JWT bearer tokens, configure a trusted issuer and require authentication for private endpoints:

spring.security.oauth2.resourceserver.jwt.issuer-uri=https://idp.example.com/issuer
@Bean
SecurityFilterChain apiSecurity(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(authorize -> authorize
            .requestMatchers("/api/public/**").permitAll()
            .anyRequest().authenticated())
        .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()));
    return http.build();
}

The resource server checks the JWT signature and claims using the issuer’s published keys. The issuer URL must be a real trusted provider with the required metadata. The API must still apply access rules to the authenticated request.

15. When does a browser application need CSRF protection?

Cross-site request forgery occurs when another site causes a browser to send an unwanted state-changing request using credentials the browser attaches automatically, such as a session cookie. A CSRF token gives the server another value to check. Servlet security enables CSRF protection for unsafe requests by default.

browser cookie + state-changing request + valid CSRF token -> process
browser cookie + state-changing request + missing token    -> reject

A server-rendered form or JavaScript client must include the token in the request. CookieCsrfTokenRepository is one option when JavaScript needs to read a token from a cookie:

http.csrf(csrf -> csrf
    .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()));

Allowing JavaScript to read the cookie is a deliberate tradeoff; use a repository that keeps HttpOnly when JavaScript does not need direct access. A stateless API can still need CSRF protection if the browser automatically sends its credentials.

16. What does CORS control, and where should Spring Security process it?

Cross-origin resource sharing lets a browser decide whether a page from one origin may read a response from another. CORS does not authenticate a caller and does not stop a non-browser client. A preflight request often has no session cookie, so CORS processing must happen before security rejects that request as unauthenticated.

@Bean
CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration cors = new CorsConfiguration();
    cors.setAllowedOrigins(List.of("https://app.example.com"));
    cors.setAllowedMethods(List.of("GET", "POST"));
    cors.setAllowedHeaders(List.of("Authorization", "Content-Type"));

    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", cors);
    return source;
}

Use http.cors(Customizer.withDefaults()) in the security chain to integrate the policy. List only the origins, methods and headers the client needs. If the application uses credentials such as cookies, configure that deliberately and test a browser preflight as well as the actual request.

17. How does session-based authentication persist between requests?

After a successful login, the application can save the SecurityContext in an HTTP session. The browser sends the session cookie on later requests; the server uses it to find the session and restore the authentication. The cookie carries an identifier, not the user’s password or the complete security context.

POST /login -> authenticate -> save SecurityContext in session
response   -> Set-Cookie: JSESSIONID=...
GET /orders with cookie -> load SecurityContext -> authorize

A session can expire or be invalidated at logout. In a distributed deployment, the session storage and cookie policy must fit the application’s architecture. A bearer-token API uses a different persistence model.

18. How can an application slow repeated login attempts?

Use a rate limit on login attempts, then add a short delay or temporary block after repeated failures. Apply limits by account and source so an attacker cannot simply rotate one identifier. Keep the response generic enough that it does not reveal whether an account exists.

login attempt -> rate limit -> authenticate
                  | too many attempts
                  v
             delay or temporary block

Spring Security verifies credentials, but the application or gateway must enforce the throttling policy. Multifactor authentication reduces the value of a guessed password; it does not replace throttling. Choose lockout rules carefully so an attacker cannot keep legitimate users locked out indefinitely.

19. How to handle Logout in Spring Security?

Session logout normally invalidates the session and clears the security context, with cookie cleanup configured as needed. It does not automatically revoke an independently valid bearer token. State which authentication mechanism the application uses when describing logout.

http.logout(logout -> logout
    .invalidateHttpSession(true)
    .deleteCookies("JSESSIONID")
    .logoutSuccessUrl("/login?logout")
    .permitAll());

Practical scenarios

20. How can an application verify password hashes during a migration?

A DelegatingPasswordEncoder reads an identifier at the start of each stored password and chooses the matching encoder. New passwords use the configured encoding identifier; old passwords can remain verifiable while users migrate.

{bcrypt}... -> BCryptPasswordEncoder
{pbkdf2}... -> Pbkdf2PasswordEncoder
new password -> current configured encoder

Record which formats are actually present before migration. Do not silently treat an unidentified legacy hash as a modern format. After a successful login, the application can re-encode when the configured encoder reports that the stored hash needs an upgrade.

21. How should a REST API enforce access rules?

Authenticate the caller, define endpoint rules, and check ownership when an operation targets a specific record. An endpoint-level role check alone cannot establish that a user may read an arbitrary order ID.

http.authorizeHttpRequests(authorize -> authorize
    .requestMatchers("/api/public/**").permitAll()
    .requestMatchers("/api/admin/**").hasRole("ADMIN")
    .anyRequest().authenticated());

The final rule covers paths not matched earlier. In the service, compare the requested record’s owner with the authenticated principal or use another explicit domain policy. Use TLS and input validation as separate protections; neither replaces authorization.

22. How should a mobile client authenticate to a Spring Security API?

A mobile app is a public client: it cannot safely keep a client secret. With an OAuth 2.0 provider, an authorization-code flow with PKCE can obtain an access token for the app. The API validates the bearer token and applies its own access rules on every request.

mobile app -> authorization server -> access token
mobile app -> Authorization: Bearer <token> -> API resource server
                                         -> validate -> authorize

A token’s presence alone is not proof of permission. Validate the token’s signature or introspection result, issuer, lifetime and intended audience as required by the API. Protect token storage on the device and plan for expiry and revocation.

23. How do you investigate an unexpected 401 or 403 response?

First identify which SecurityFilterChain matched the request. A 401 response generally means the request needs authentication; a 403 response generally means the request was authenticated but the access rule denied it. The configured entry point and access-denied handler determine the exact response.

request -> matching SecurityFilterChain?
            -> no usable Authentication -> entry point (often 401)
            -> Authentication present, rule denies -> access denied (often 403)

Enable Spring Security debug logging in a development environment and inspect the selected filter chain, the request matcher, the authentication mechanism and the authorities. Check a method-security rule too if the endpoint rule allows the request but the service method denies it. Avoid logging credentials or complete bearer tokens.

Conclusion

For an interview, explain the request path first, then identify where authentication ends and authorization begins. Use the same flow to diagnose a denied request in an application.

Happy Learning!

Leave a Comment

  1. Appreciate the efforts of this publisher. Great overview of the entire spring-security module. Thanks bro 🙏 🙌

Comments are closed.

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.