Spring Security · mid
The filter chain and JWT resource servers
Spring Security is a chain of servlet filters. A resource server checks the JWT signature, issuer and expiry. Use the issuer address so key rotation works.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- The servlet container has one filter,
DelegatingFilterProxy, which hands over toFilterChainProxy. It picks the first matchingSecurityFilterChain. Several chains can exist withsecurityMatcher("/api/**")and@Order. - The authenticated user is in the
SecurityContextHolder(a ThreadLocal by default). Stateless chains do not store it in a session. - 401 = not authenticated (
AuthenticationEntryPoint). 403 = authenticated but not allowed (AccessDeniedHandler). - JWT:
oauth2ResourceServer(o -> o.jwt(...))checks signature, expiry, issuer and audience. Prefer it over a hand-written filter. - Property:
spring.security.oauth2.resourceserver.jwt.issuer-uri=...finds the key set and checksiss. - Rules:
authorizeHttpRequests(a -> a.requestMatchers("/actuator/health/**").permitAll().requestMatchers("/api/admin/**").hasRole("ADMIN").anyRequest().authenticated()). Order matters: specific first,anyRequest()last. - By default the
scopeclaim maps toSCOPE_...authorities. For Keycloak'srealm_access.roleswrite a converter.hasRole("ADMIN")addsROLE_itself. - Spring Security 7 (Boot 4) accepts only the lambda DSL:
and()andauthorizeRequests()are gone. Key rotation: withissuer-urithe decoder fetches and caches the key set and picks up new keys. A fixedpublic-key-locationbreaks when the provider rotates: "No matching key(s) found" and every request gets 401. Tests:@WebMvcTestwith thejwt()request post-processor: 401 without a token, 403 for a normal user, 200 for admin.
The red pen
Common traps: mistake → fix
Mistake: A fixed public key file is simpler and safe
Fix: it breaks on key rotation.
Mistake: 401 and 403 mean the same
Fix: 401 is unauthenticated, 403 is forbidden.
Mistake: Roles come from the token automatically
Fix: default is SCOPE_ authorities; custom claims need a converter.
Easy to hard
Questions interviewers ask, easy to hard
- What happens before a request reaches your controller with Spring Security?
- Where is the JWT checked?
- Configure /api/** for JWT, /api/admin/** for admins, health open.
- One of twelve services returns 401 after the identity provider rotated keys. Why?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.