πŸš€ Spring Security: Bearer Token Authentication with AuthenticationFilter (New Approach)

πŸ”₯ Here’s the quick & modern way to authenticate JWT Bearer tokens in Spring Security 6+.


1️⃣ SecurityConfig – Register AuthenticationFilter


@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationFilter authenticationFilter) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .addFilterAt(authenticationFilter, UsernamePasswordAuthenticationFilter.class) // Inject JWT Filter
            .authorizeHttpRequests(auth -> auth.anyRequest().authenticated());

        return http.build();
    }

    @Bean
    public AuthenticationFilter authenticationFilter(JwtAuthenticationManager authenticationManager) {
        return new AuthenticationFilter(authenticationManager, new JwtAuthenticationConverter());
    }
}

πŸš€ No more custom OncePerRequestFilter! AuthenticationFilter does it all.


2️⃣ JwtAuthenticationConverter – Extract Bearer Token

java
CopyEdit
public class JwtAuthenticationConverter implements AuthenticationConverter {

    @Override
    public Authentication convert(HttpServletRequest request) {
        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            return new UsernamePasswordAuthenticationToken(token.substring(7), null);
        }

        return null; // No token, no authentication
    }
}

βœ… Extracts JWT from the Authorization header.

βœ… Converts it into a Spring Authentication object.


3️⃣ JwtAuthenticationManager – Validate JWT


@Component
public class JwtAuthenticationManager implements AuthenticationManager {

    private final JwtService jwtService;

    public JwtAuthenticationManager(JwtService jwtService) {
        this.jwtService = jwtService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String token = (String) authentication.getPrincipal();

        if (!jwtService.isValid(token)) {
            throw new BadCredentialsException("Invalid JWT");
        }

        return new UsernamePasswordAuthenticationToken(jwtService.getUser(token), null, jwtService.getRoles(token));
    }
}

βœ… Validates the JWT

βœ… Retrieves the user & roles


4️⃣ JwtService – Handles JWT Logic

java
CopyEdit
@Component
public class JwtService {

    public boolean isValid(String token) {
        // TODO: Validate token (e.g., using JWT library)
        return true;
    }

    public String getUser(String token) {
        // TODO: Extract username from token
        return "[email protected]";
    }

    public List<GrantedAuthority> getRoles(String token) {
        // TODO: Extract roles
        return List.of(new SimpleGrantedAuthority("ROLE_USER"));
    }
}

βœ… Token validation, user extraction, and role assignment.