spring security in action second edition
We use cookies to store your preferences, such as language selected. No personal data is stored.

Spring Security In Action Second Edition Link -

The most critical piece from the second edition is the custom filter. It intercepts every request, grabs the Authorization: Bearer header, and populates the SecurityContextHolder for that request only (because there is no session to carry it forward).

@Configuration @EnableWebSecurity public class StatelessSecurityConfig @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception http .sessionManagement(session -> session .sessionCreationPolicy(SessionCreationPolicy.STATELESS) ) .authorizeHttpRequests(auth -> auth .requestMatchers("/login", "/refresh").permitAll() .anyRequest().authenticated() ); // No formLogin() - we use a custom filter return http.build(); spring security in action second edition

@Component public class JwtService private final SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256); private final long EXPIRATION = 86400000; // 24 hours public String generateToken(String username) return Jwts.builder() .setSubject(username) .setIssuedAt(new Date()) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION)) .signWith(key) .compact(); The most critical piece from the second edition

To go stateless, we need to disable session creation entirely: grabs the Authorization: Bearer header