Skip to the page

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.

The notes

What you must know

  • The servlet container has one filter, DelegatingFilterProxy, which hands over to FilterChainProxy. It picks the first matching SecurityFilterChain. Several chains can exist with securityMatcher("/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 checks iss.
  • Rules: authorizeHttpRequests(a -> a.requestMatchers("/actuator/health/**").permitAll().requestMatchers("/api/admin/**").hasRole("ADMIN").anyRequest().authenticated()). Order matters: specific first, anyRequest() last.
  • By default the scope claim maps to SCOPE_... authorities. For Keycloak's realm_access.roles write a converter. hasRole("ADMIN") adds ROLE_ itself.
  • Spring Security 7 (Boot 4) accepts only the lambda DSL: and() and authorizeRequests() are gone. Key rotation: with issuer-uri the decoder fetches and caches the key set and picks up new keys. A fixed public-key-location breaks when the provider rotates: "No matching key(s) found" and every request gets 401. Tests: @WebMvcTest with the jwt() 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

  1. What happens before a request reaches your controller with Spring Security?
  2. Where is the JWT checked?
  3. Configure /api/** for JWT, /api/admin/** for admins, health open.
  4. 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 voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview