AuthenticationFilter
(New Approach)π₯ Hereβs the quick & modern way to authenticate JWT Bearer tokens in Spring Security 6+.
@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.
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.
@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
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.