Most JWT setups on top of Spring Security look fine in a demo and fall apart in production: roles never match the expected authority string, logout doesn't actually revoke anything, and half the protected endpoints return 403 instead of 401. The root cause is almost never the token's cryptography, it's a shallow understanding of the filter chain the token has to plug into.

The "it works" tutorial trap

The pattern copied from most tutorials is a single filter that reads the Authorization header, decodes the JWT, and pushes an Authentication into the SecurityContextHolder. That's enough to pass a login call and one manually tested protected route. Then the real issues surface: authentication failures bubble up as 500s instead of 401s, business-level roles like "ADMIN" never match Spring's hasRole("ADMIN") (which expects a ROLE_ prefix), and nobody has a plan for invalidating a token before it expires.

These aren't unrelated bugs. They all trace back to the same misunderstanding: Spring Security isn't "a filter that checks a token," it's an ordered chain of filters with a strict contract about who throws what, when, and how that gets translated into an HTTP response.

How the filter chain actually works

Since Spring Security 5.7 (and mandatory in 6.x), WebSecurityConfigurerAdapter is gone in favor of an explicit SecurityFilterChain bean. For a stateless API, three decisions shape everything downstream: disable session management, place the JWT filter before UsernamePasswordAuthenticationFilter, and define an AuthenticationEntryPoint that returns JSON and a 401 instead of the default redirect to a login page.

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;

    public SecurityConfig(JwtAuthenticationFilter jwtAuthFilter,
                           AuthenticationProvider authenticationProvider) {
        this.jwtAuthFilter = jwtAuthFilter;
        this.authenticationProvider = authenticationProvider;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
            .csrf(AbstractHttpConfigurer::disable)
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/api/auth/**").permitAll()
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated()
            )
            .sessionManagement(session ->
                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .exceptionHandling(ex -> ex
                .authenticationEntryPoint((req, res, e) -> {
                    res.setContentType("application/json");
                    res.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    res.getWriter().write("{\"error\":\"unauthorized\"}");
                })
            )
            .authenticationProvider(authenticationProvider)
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
            .build();
    }
}

Disabling CSRF here is not a careless shortcut: CSRF protection exists because browsers attach cookies automatically to requests. Without a session cookie, there's no CSRF surface to defend, provided the token itself isn't stored in a cookie without SameSite set correctly (more on storage below).

Issuing and validating the token correctly

The signing algorithm matters. HS256 (symmetric) is simple but means sharing the secret with every service that needs to validate the token; RS256 (asymmetric) lets a service verify a token with a public key without ever holding the private key that signed it, which becomes the better default once more than one microservice needs to check tokens.

@Component
public class JwtService {

    private final SecretKey signingKey;
    private static final long ACCESS_TOKEN_TTL_MS = 15 * 60 * 1000; // 15 minutes

    public JwtService(@Value("${jwt.secret}") String secret) {
        this.signingKey = Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
    }

    public String generateAccessToken(UserDetails user) {
        Instant now = Instant.now();
        return Jwts.builder()
            .subject(user.getUsername())
            .claim("roles", user.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority).toList())
            .issuedAt(Date.from(now))
            .expiration(Date.from(now.plusMillis(ACCESS_TOKEN_TTL_MS)))
            .signWith(signingKey)
            .compact();
    }

    public Claims validate(String token) {
        return Jwts.parser()
            .verifyWith(signingKey)
            .build()
            .parseSignedClaims(token)
            .getPayload();
    }
}

A detail that comes up constantly in review: roles stored in the claim need the ROLE_ prefix if you intend to call hasRole(), or you use hasAuthority() with the raw string instead. Mixing the two conventions is the single most common cause of mysterious 403s on endpoints that are, on paper, correctly protected.

The JWT authentication filter

The filter should do exactly one thing: extract the token, validate it, build an Authentication, and set it on the context. It should never decide on its own whether to return 401 or 403; that responsibility belongs to the exception handling configured above.

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtService jwtService;
    private final UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                     HttpServletResponse response,
                                     FilterChain filterChain) throws ServletException, IOException {
        String header = request.getHeader("Authorization");
        if (header == null || !header.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = header.substring(7);
        try {
            Claims claims = jwtService.validate(token);
            UserDetails user = userDetailsService.loadUserByUsername(claims.getSubject());
            var auth = new UsernamePasswordAuthenticationToken(
                user, null, user.getAuthorities());
            auth.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(auth);
        } catch (JwtException | IllegalArgumentException ex) {
            SecurityContextHolder.clearContext();
        }

        filterChain.doFilter(request, response);
    }
}

Letting the request continue down the chain even when validation fails (rather than short-circuiting inside the filter) is deliberate: authorizeHttpRequests further down decides whether the route actually requires authentication, and exceptionHandling produces the right response if it does.

Diagnosing the usual suspects

Three symptoms show up again and again in review:

  • Expected 401, got 403: almost always a filter ordering issue, or an authorizeHttpRequests rule matching the route before the JWT filter got a chance to populate the context.
  • "Access denied" on a role that looks correct: check the ROLE_ prefix and exact casing of the claim against the hasRole/hasAuthority expression.
  • Token expires mid-burst of concurrent requests: a poorly handled refresh flow on the client fires several parallel refresh calls, and only one should succeed; without a client-side lock (or an idempotent rotation on the server), you get race conditions that log users out at random.

Where to store the token on the client

The storage choice on the browser side determines which attack family you're accepting. A token in localStorage is readable by any script running on the page, so it's vulnerable to any XSS flaw, even a minor one, that lets an attacker exfiltrate it to a third-party domain. An httpOnly cookie isn't readable by JavaScript, which neutralizes that vector, but reintroduces a CSRF surface since the browser attaches it automatically to every request to that domain.

@PostMapping("/api/auth/login")
public ResponseEntity<Void> login(@RequestBody LoginRequest req, HttpServletResponse response) {
    String token = authenticate(req);
    ResponseCookie cookie = ResponseCookie.from("access_token", token)
        .httpOnly(true)
        .secure(true)
        .sameSite("Strict")
        .path("/api")
        .maxAge(Duration.ofMinutes(15))
        .build();
    response.addHeader(HttpHeaders.SET_COOKIE, cookie.toString());
    return ResponseEntity.ok().build();
}

With SameSite=Strict (or Lax depending on cross-site navigation needs), the cookie simply isn't sent on a request originating from another domain, which covers most of the CSRF risk without re-enabling Spring's classic CSRF protection. The right tradeoff depends on the risk profile: an API consumed only by a frontend you control tolerates an httpOnly cookie well; a public API consumed by a variety of third-party clients (mobile apps, server-to-server scripts) fits better with a plain Authorization header, where XSS risk only applies in the first place if the client happens to be a web page.

The real problem: revocation

A stateless, signed JWT cannot be invalidated before it expires without some server-side state. Three realistic options:

  1. Short TTL, no revocation: a 10-15 minute access token, acceptable when the residual risk window after a logout is tolerable for the business.
  2. Database-backed refresh token with rotation: every refresh issues a new refresh token and invalidates the old one; if an already-used refresh token is presented again, that's a theft signal, and the entire token family for that user gets revoked.
  3. A revocation list (by jti) in Redis: a cache lookup on every request, but it buys an immediate logout and a real "sign out everywhere" feature.

When the easy fix isn't enough

If the product has an explicit requirement like "an admin must be able to force-disconnect a user immediately," none of the purely stateless variants satisfy it: a server-side lookup, and therefore some shared state, becomes necessary. That's not a failure of the JWT approach, it's an accepted tradeoff between stateless scalability and fine-grained session control. A single O(1) Redis lookup per request is still far cheaper than loading a full session from a relational database, so the tradeoff pays off in the vast majority of cases.

Correct JWT authentication isn't about which signing library you pick, it's about a correctly ordered filter chain and an explicit decision on what is and isn't revocable. Treating revocation as a detail to figure out later reliably produces a logout button that logs nobody out.