Articles
Spring Security Interview Questions: Filter Chains, CSRF, and Authentication Failures
Practice Spring Security interview questions on filter-chain matching, CSRF, 401 and 403 failures, credential transport, and focused security regression tests.
A Spring endpoint can use permitAll() and still return 403. Another endpoint can require an administrator inside one configuration and accidentally run through a different filter chain. These failures are difficult to explain if your entire mental model is “Spring checks the JWT.”
Strong Spring Security interview answers trace a specific request: which chain selected it, which filter first rejected it, what authentication existed at that point, and which response handler ran. Changing a role rule before identifying those boundaries can hide the original problem while opening a new one.
Evidence boundary: This guide covers Servlet applications using the current Spring Security reference, which displayed version 7.1.1 when checked in September 2026. Verify APIs against your project version; WebFlux uses a different security stack. Official behaviors are linked below. The diagnostic exercises are original examples, not candidate reports or predictions of an employer’s questions.
Use Assess Spring IoC, AOP, JDBC, Security to practice explaining the mechanism before proposing a configuration change.
Which filter chain actually handles the request?
Official fact: Spring’s Servlet architecture uses DelegatingFilterProxy to connect the container to a Spring-managed filter. FilterChainProxy selects a SecurityFilterChain; only the first matching chain runs. Its filters have an order, and a filter can stop processing before the request reaches the controller. Spring Security architecture.
That is different from combining every matching configuration into one policy. Imagine an early chain matching all requests and a later chain intended for /admin/**. The later chain’s stricter rules do not rescue requests already selected by the first chain.
Interview inference: Start a debugging answer by asking for the request method, path as seen by the application, dispatcher type, configured chain order, and security logs. A reverse proxy’s public URL may differ from the path your matcher evaluates. Do not infer chain selection solely from a controller annotation or a configuration class name.
Write the selected chain beside the request on your diagram. Then list only the filters belonging to that chain. This prevents a common explanation error: discussing a bearer-token filter that was never part of the failing request’s execution path.
How do securityMatcher and requestMatchers differ?
Official fact: securityMatcher limits where an entire HttpSecurity configuration applies. Matchers inside authorizeHttpRequests choose authorization rules within the selected chain. A request matching no chain is not protected by Spring Security’s filter chains. Spring recommends a fallback chain covering remaining requests. Java configuration.
Consider this original routing exercise, expressed as policy rather than copy-ready Java configuration:
- Chain A, first:
/api/**; API authentication and API authorization rules. - Chain B, second:
/admin/**; browser login and administrator rules. - Chain C, last: every remaining request; explicitly public pages and a restrictive default.
| Request | Chain |
|---|---|
/api/orders | A |
/admin/users | B |
/api/admin/report | A |
/help | C |
The third row is the trap. Including the word “admin” does not make the path match /admin/**. Explain which chain owns this endpoint, then define its administrator rule inside that chain if that is the requirement.
Now remove C. /help no longer has the intended Spring Security coverage. It may still encounter application or infrastructure checks, but those do not make the missing chain correct. Add a test for an unexpected new path so a future controller does not inherit an accidental security gap.
A second variation puts the catch-all chain first. Every row then selects it. Compare these outcomes before discussing credentials: no token change can repair a routing policy that chooses the wrong chain.
Why can permitAll still produce a 403?
Official fact: permitAll is an authorization rule, not a request to bypass the whole security stack. Spring explicitly distinguishes permitting a request from ignoring it, including the ability to apply security headers. Authorization rules are evaluated in their configured order. Request authorization.
Official fact: Spring’s CSRF filter checks protected requests and passes missing or invalid tokens to an access-denied handler. With the default denial behavior, that can produce 403 before a controller handles the request. Servlet CSRF protection.
Diagnostic inference: For a public POST returning 403, inspect the rejecting filter and CSRF evidence before widening access rules. A public signup endpoint can still need protection against unwanted cross-site submissions. “Public” answers who needs authentication; it does not answer every abuse or browser-security question.
Use a controlled comparison: send the same request with a valid token associated with the expected repository state, then with no token, then with an invalid token. Keep the path, method, body, and identity otherwise unchanged. If the failure changes, you have narrowed the hypothesis; you have not yet proved the whole endpoint safe.
Avoid “fixing” the symptom by disabling every security filter in a test. That only demonstrates that the controller works without the component under investigation.
Does stateless authentication mean CSRF is unnecessary?
Official fact: Spring’s CSRF guidance warns that stateless browser applications can remain vulnerable. A custom authentication cookie is still automatically sent by the browser; browser-managed Basic credentials can also create CSRF exposure. Moving state out of a server session does not remove that credential behavior. CSRF fundamentals.
Design inference: Ask how credentials reach the request. A bearer token deliberately attached in an authorization header by a trusted client has a different CSRF threat model from a token carried in an automatically attached cookie. Calling both systems “JWT authentication” hides the distinction that matters.
For a mixed application, document credential transport per route group. Browser pages, machine clients, and embedded widgets may require different policies. A carefully scoped CSRF exception needs an explicit reason and regression tests; a blanket exception based on the /api name does not establish that reason.
Also ask whether any GET changes state. Designing supposedly safe methods to perform mutations undermines assumptions in browser protections and caches. Separately evaluate token theft, cross-site scripting, and unauthorized access: choosing a CSRF policy does not solve those problems.
How are authentication and authorization connected?
Official fact: Authentication represents either credentials submitted for authentication or the resulting principal and authorities. Authentication filters use an AuthenticationManager; a common implementation, ProviderManager, delegates to supporting providers. The resulting authentication is available through the security context. Authentication architecture.
In an interview, distinguish “a credential was present” from “a trusted authentication was established.” A custom filter that merely decodes token claims has not necessarily verified the token or proved that the caller may act as that principal.
Design inference: Inspect the actual authorities produced after authentication. If the route expects an administrator authority, a valid identity with an ordinary user authority should still fail. Check mapping and naming conventions instead of adding broad permissions until a test turns green.
URL authorization also does not establish ownership of a particular order. For GET /orders/123, ask whether this authenticated user may view order 123, not just whether the path begins with /orders. Put the resource-level check at a boundary that cannot be bypassed by another caller of the underlying operation.
The useful follow-up is a negative example: user A is authenticated and can view A’s order, but receives the intended denial when requesting B’s order. That demonstrates a meaningful policy beyond a successful login.
Does 401 always mean authentication and 403 always mean authorization?
Official fact: ExceptionTranslationFilter translates downstream authentication and access-denied failures into configured handling. Starting authentication invokes an AuthenticationEntryPoint; an authenticated access denial uses an AccessDeniedHandler. Entry points and other authentication components can produce different responses, including login redirects. Exception translation in the architecture guide.
Diagnostic inference: Status codes are clues, not complete traces. A browser login flow may redirect an unauthenticated request, while an API returns an authentication challenge. A CSRF failure may return 403 without demonstrating that credentials were successfully checked. A custom handler can also change the visible status or body.
Record the first rejection, exception category where applicable, and handler. Do not assume the exception translator catches every exception from every custom filter: filter position and each filter’s own failure handling matter. An upstream failure does not become downstream merely because the application uses Spring Security.
The illustration is a diagnostic checklist, not an exhaustive filter-order diagram; an existing session context may already be loaded before CSRF checks. If a team sees a redirect loop, investigate whether the login page itself is protected and whether the expected login endpoint belongs to the selected chain. If a client sees HTML where it expected JSON, inspect the entry point rather than immediately blaming response serialization.
How would you test a cookie-authenticated POST?
Use the following original matrix for a hypothetical POST /profile/email. Assume CSRF is enabled, the endpoint requires authentication, denial returns 403, and the configured API entry point returns 401. The controller returns 204 only when its valid business operation succeeds.
| Identity and token | Expected checkpoint |
|---|---|
| No identity, no CSRF | CSRF denial first |
| No identity, valid CSRF | Authentication needed |
| Signed in, invalid CSRF | CSRF denial |
| Signed in, valid CSRF | Authorization and controller |
The last row does not promise success for every request body or principal. Add wrong-owner, validation-failure, and application-error cases separately. Likewise, a syntactically plausible token string is not “valid CSRF” unless it matches the repository and request expectations.
Official fact: Spring’s MockMvc support provides csrf() for valid tokens, a header variant, and useInvalidToken() for negative tests. Testing CSRF protection.
Testing recommendation: Combine a controlled principal with these token cases to isolate authorization and CSRF behavior. Then add separate tests exercising the real credential-processing mechanism. Injecting a mock user does not verify password checking, bearer-token validation, or login persistence.
Confirm that the test includes the intended security filter chain. A controller-only test with filters omitted cannot catch an incorrect chain order. Verify both the response and whether the protected business operation executed; a denied response after an unintended mutation is not a successful security test.
What evidence makes a troubleshooting answer convincing?
Offer a bounded sequence. Reproduce one failing request in a suitable test environment. Identify its chain, capture the first rejecting component, inspect non-secret authentication metadata, and compare one deliberately changed input. Only then propose the smallest policy or client change that explains the evidence.
Do not log passwords, full authorization headers, session cookies, or CSRF token values to make the trace convenient. Useful evidence includes a correlation identifier, selected chain, filter name, authentication category, relevant authority names when appropriate, and sanitized failure classification.
Include dispatcher behavior when an original error becomes a confusing second denial. An error rendering request may encounter security rules too; inspect both dispatches instead of treating the final response as proof of the original cause. Apply any exception narrowly and test that it does not expose protected content through alternate dispatch paths.
Finish by stating what would disprove the hypothesis. If a valid CSRF token leaves the same earlier rejection unchanged, inspect chain selection or another filter. If authentication succeeds but access fails, examine authorities and resource ownership. This gives the interviewer a repeatable diagnosis rather than a collection of configuration guesses.
Sources and Further Reading
- Spring Security Servlet architecture — chain selection, filters, and exception handling.
- Java security configuration — chain coverage and matcher scope.
- Request authorization — authorization rules and permitting versus ignoring.
- Servlet CSRF protection — token validation and denial behavior.
- CSRF fundamentals — browser credentials and stateless applications.
- Authentication architecture — managers, providers, and security context.
- MockMvc CSRF testing — valid and invalid token test helpers.