Spring Security interview questions and answers for Java backend roles

Most Spring Security interview questions come down to one picture: a chain of servlet filters that authenticates the request, stores the result in a SecurityContext, and then decides whether the caller may reach the URL or method. Interviewers ask you to explain that chain, configure it with a SecurityFilterChain bean, choose between sessions and JWTs, and debug the 401s and 403s that follow. Naming the filter or component responsible for each behavior is what separates a strong answer from a memorized one.

By Published 6 min read

Where Spring Security shows up in interviews

Java backend and full-stack interviews rarely stop at "we used Spring Security". After the Spring Boot interview questions on beans and configuration, a panel will usually ask how a request is authenticated, why an endpoint returns 403, or how you would secure a REST API for a single-page app. Token formats, grant types and OpenID Connect are covered in OAuth and JWT interview questions; this page is about how Spring wires those ideas into a running app.

  1. Servlet container
    • DelegatingFilterProxy
  2. Spring Security
    • FilterChainProxy
    • Matching SecurityFilterChain
  3. Security filters
    • CsrfFilter
    • Authentication filters
    • ExceptionTranslationFilter
    • AuthorizationFilter
  4. Application
    • DispatcherServlet
    • Controller
How a request passes through Spring Security. The servlet container calls DelegatingFilterProxy, a normal servlet filter. It hands the request to the FilterChainProxy bean, which picks the first SecurityFilterChain whose matcher fits the URL. That chain runs security filters such as CSRF, authentication, exception translation and authorization, and only then does the request reach the DispatcherServlet and your controller.

Fundamentals: architecture and authentication

Questions most candidates get in the first round
QuestionWhat it testsWhat a strong answer shows
Authentication versus authorization?VocabularyAuthentication establishes who the caller is. Authorization decides what that caller may do. Spring runs the first in authentication filters and the second in the authorization filter or method interceptors.
What does DelegatingFilterProxy do?Container bridgeIt is a plain servlet filter registered with the container that looks up a Spring bean and delegates to it. That lets security filters be Spring beans with injected dependencies.
What is FilterChainProxy?Chain selectionThe bean behind the proxy. It holds one or more SecurityFilterChain objects and runs the first one whose request matcher fits, which is how an API and an admin UI can have different rules.
How does a username and password login reach the database?Auth flowA filter builds an unauthenticated token, the AuthenticationManager (usually ProviderManager) asks its providers, DaoAuthenticationProvider loads the user through UserDetailsService and checks the password with the PasswordEncoder.
What is stored in the SecurityContext?ContextAn Authentication object with the principal, its granted authorities and whether it is authenticated. Code reads it through SecurityContextHolder.
How does SecurityContextHolder keep data per request?Thread modelIts default strategy uses a ThreadLocal, so the context belongs to the request thread. Work handed to another thread does not see it unless you propagate it.
Why use DelegatingPasswordEncoder?Password storageStored hashes carry a prefix such as {bcrypt}, so the app can verify old formats while encoding new passwords with the current algorithm, and upgrade hashes as users log in.
What happens when you add Spring Security to a Boot app with no configuration?DefaultsEvery endpoint requires authentication, form and basic login are enabled, and a generated password for a default user is printed in the startup log. It is a starting point, not a production setup.
hasRole versus hasAuthority?AuthoritieshasRole("ADMIN") checks for the authority ROLE_ADMIN. hasAuthority checks the exact string, which is how OAuth scopes such as SCOPE_orders.read are usually tested.
What is an AuthenticationEntryPoint?Unauthenticated callsThe component that starts authentication when an anonymous user hits a protected resource: a redirect to the login page for browsers, or a 401 with a WWW-Authenticate header for APIs.
Questions most candidates get in the first round. Scroll sideways on a small screen.

Configuring the filter chain

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    @Order(1)
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.securityMatcher("/api/**")
            .authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/api/products/**").permitAll()
                .requestMatchers("/api/admin/**").hasAuthority("SCOPE_admin")
                .anyRequest().authenticated())
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .csrf(csrf -> csrf.disable())          // bearer tokens, no session cookie
            .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()));
        return http.build();
    }

    @Bean
    @Order(2)
    SecurityFilterChain web(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers("/login", "/css/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .formLogin(Customizer.withDefaults());
        return http.build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}
Two chains: a stateless JWT API and a form-login admin area. Not executed; it needs Spring Security and the OAuth2 resource server module. The issuer is set through configuration.
  • Why does the order of requestMatchers matter? Rules are checked top to bottom and the first match wins. Putting anyRequest().authenticated() or a broad pattern first makes the narrower rules after it unreachable.
  • What replaced WebSecurityConfigurerAdapter? Declaring SecurityFilterChain beans, as above. The adapter was deprecated in the 5.x line and removed in Spring Security 6, so migration questions about it are common for teams on older apps.
  • When is it safe to disable CSRF protection? When the API authenticates with a bearer token in a header and never relies on cookies the browser sends automatically. If a session cookie or cookie-stored token authenticates the call, keep CSRF on.
  • permitAll or web.ignoring() for static files? Prefer permitAll. Ignoring skips the whole chain, including security headers and the security context, and the reference documentation recommends against it for most paths.
  • Why does a browser preflight fail with 401 or 403? The OPTIONS request has no credentials and was rejected by security before CORS handling. Enable http.cors(...) with a CorsConfigurationSource so preflights are answered first.
  • How do you add a custom filter, such as an API key check? Write a OncePerRequestFilter and place it with addFilterBefore relative to a known filter, for example before the username and password filter. Avoid also registering it as a plain servlet filter, or it runs twice.

Method security, sessions and tokens

Intermediate and senior questions
QuestionWhat it testsWhat a strong answer shows
How does @PreAuthorize work?Method securityWith method security enabled, Spring wraps the bean in a proxy that evaluates the SpEL expression before the call, for example hasRole('ADMIN') or #userId == authentication.name.
Why is @PreAuthorize ignored on a method called from the same class?ProxiesThe call does not go through the proxy, so no check runs. Move the method to another bean or check access at the entry point that is proxied.
URL rules or method rules?DesignURL rules are coarse and easy to see in one place. Method rules sit next to the business logic and protect it whichever controller or job calls it. Many apps use both, with object-level checks in methods.
How is session fixation handled?SessionsBy default the session ID is changed when a user logs in, so an ID planted before login cannot be reused. You can configure it, but turning it off is rarely justified.
How do you limit one active session per user?Concurrency controlSession management with maximum sessions set to one, plus a choice of rejecting the new login or expiring the old one. It needs a session registry and session events to work.
What does the JWT resource server validate?Token checksSignature against keys from the issuer, expiry and not-before times, and the issuer. Audience checks are something you often add yourself, so ask how the team configures it.
How do JWT claims turn into authorities?MappingBy default scopes become authorities with a SCOPE_ prefix. A JwtAuthenticationConverter maps a custom claim, such as roles, to ROLE_ authorities instead.
Sessions or JWTs for a single-page app on the same domain?JudgmentA server session with an HttpOnly cookie and CSRF protection is often simpler and easier to revoke. Tokens suit separate API consumers and services. A strong answer weighs revocation, XSS exposure and scaling, not fashion.
Your @Async method sees no logged-in user. Why?Context propagationThe task runs on another thread without the ThreadLocal context. Wrap the executor with a delegating security context executor or pass the needed identity explicitly.
401 versus 403 from Spring Security?Error pathsExceptionTranslationFilter turns an authentication failure into the entry point, typically 401 or a login redirect. An access denial for an authenticated user goes to the AccessDeniedHandler, typically 403.
Intermediate and senior questions. Scroll sideways on a small screen.
@WebMvcTest(OrderController.class)
@Import(SecurityConfig.class)
class OrderSecurityTest {

    @Autowired MockMvc mvc;

    @Test
    void anonymousCallerIsRejected() throws Exception {
        mvc.perform(get("/api/orders/7")).andExpect(status().isUnauthorized());
    }

    @Test
    void readerScopeCanReadButNotDelete() throws Exception {
        mvc.perform(get("/api/orders/7").with(jwt().authorities(new SimpleGrantedAuthority("SCOPE_orders.read"))))
           .andExpect(status().isOk());
        mvc.perform(delete("/api/admin/orders/7").with(jwt()))
           .andExpect(status().isForbidden());
    }

    @Test
    @WithMockUser(roles = "ADMIN")
    void adminPageNeedsAdminRole() throws Exception {
        mvc.perform(get("/admin/reports")).andExpect(status().isOk());
    }
}
Testing rules with spring-security-test and MockMvc. Not executed; it needs a Spring test context.
  • How do you test that a form POST needs a CSRF token? Send it once without a token and expect 403, then once with .with(csrf()) and expect success.
  • Where should object-level checks live, such as "a user may only read their own orders"? In the service, either in the query (filter by owner) or with a method security expression or custom authorization component. URL patterns cannot see which order belongs to whom.
  • How do you log out a user who holds a JWT? You cannot recall a self-contained token, so keep access tokens short-lived, revoke refresh tokens, and add a deny list only where the risk justifies the lookup.
  • How would you find out which filters run for a request? Turn on debug logging for the security package or enable the debug flag on web security in a local environment, then read the filter list and the matched chain.

Fictional example

Answering "After upgrading, every POST from our React app returns 403"
Interviewer
We upgraded Spring Boot and Spring Security. GET calls from the React app still work, but every POST now returns 403. What would you check?
Candidate
A 403 on writes only, with reads still working, points to CSRF before anything else. I would check whether the app authenticates with a session cookie; if it does, CSRF protection is correct and the question is how the token reaches the client. Newer versions changed how the CSRF token is loaded and handled, so a setup that used to read it from a cookie can stop working without config changes. I would turn on security debug logging, confirm the CsrfFilter is the one rejecting the call, then configure a cookie-based token repository and the matching request handler that the reference docs describe for single-page apps, and add a MockMvc test that posts with and without the token so the next upgrade cannot silently break it.

A practice plan for Spring Security

  • Session 1: add Spring Security to a small Boot app, read the generated password in the log, then replace it with an in-memory user and a delegating password encoder.
  • Session 2: draw the filter chain from memory, then turn on debug logging and compare your drawing with the real filter list.
  • Session 3: build two chains, a stateless API and a form-login area, and prove the boundaries with MockMvc tests.
  • Session 4: protect a service method with @PreAuthorize, call it from inside the same class, and explain why the check vanished.
  • Session 5: connect a resource server to a local identity provider or a test issuer, map a roles claim to authorities, and walk through 401 versus 403 out loud.

Related pages: Servlet interview questions explains the filter model that Spring Security builds on, and SoapUI interview questions covers testing secured web services from the tester's side, including WS-Security headers.

Security answers fall apart when the order of components gets muddled mid-sentence. Natively, an AI interview assistant on Mac and Windows, transcribes your mock round on your computer so you can check whether you described the chain in the right sequence. While practicing, it can read a configuration class or an error log from a screenshot and suggest which filter to look at. With Pro or the free trial it also uses the résumé and job description you add, and the transcript and notes remain available afterward.

Questions people ask

What Spring Security questions are asked in interviews?

How the filter chain works, how a login reaches UserDetailsService and the PasswordEncoder, URL versus method authorization, CSRF and CORS, sessions versus JWTs, and why a request returns 401 or 403.

What replaced WebSecurityConfigurerAdapter?

Configuration through SecurityFilterChain beans built from HttpSecurity. The adapter was deprecated in the 5.x line and removed in Spring Security 6.

Should CSRF be disabled for a REST API?

Only when the API authenticates with a token sent in a header rather than a cookie the browser attaches automatically. Cookie or session based APIs still need CSRF protection.

What is the difference between hasRole and hasAuthority?

hasRole adds the ROLE_ prefix before checking, so hasRole("ADMIN") looks for ROLE_ADMIN. hasAuthority compares the exact string, which suits OAuth scopes such as SCOPE_read.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP