Video in progress

Strong Middle 🌱 Spring

How do you build stateless JWT authentication with Spring Security?

Don't write your own filter; use oauth2ResourceServer().jwt(). Spring reads the token, checks the signature and expiry, and turns it into an Authentication. No session is opened.

📖 Answer

@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    return http
        .csrf(c -> c.disable())   // no cookies, the token is in a header
        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .authorizeHttpRequests(a -> a
            .requestMatchers("/api/auth/**").permitAll()
            .anyRequest().authenticated())
        .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
        .build();
}
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://auth.shop.uz/realms/shop   # Keycloak, etc.

If you issue the token yourself, give NimbusJwtDecoder.withPublicKey(...) the public key. Distributing a symmetric (HS256) key to several services is risky: every one of them can then mint tokens.

A few more points:

  • keep the access token short-lived (5-15 minutes), because it's hard to revoke a JWT before it expires;
  • for a long session you need a refresh token; store it on the server so you can revoke it;
  • don't put secrets in the token: it is signed, not encrypted;
  • take roles from the scope/roles claim with a JwtAuthenticationConverter.

Many projects write their own JwtFilter, but it's very easy to miss something in it, like the signature algorithm, the expiry, or alg: none.