SPRING BOOT :Spring Security circular bean dependency

Solution 1:

Spring security has had full JWT support since 2018, so my recommendation is the following.

Remove all the custom code since writing custom security is bad practice. Use the built in JWT functionality that comes with spring security.

First define that you want to use the oauth2resource filter but you want the filter to handle jwts instead of a traditional oauth2 token.

@EnableWebSecurity
public class DirectlyConfiguredJwtDecoder extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) {
        http
            .authorizeHttpRequests(authorize -> authorize
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    }
}

add a custom decoder, that will decode the jwt using the built in Nimbus library that comes with Spring Security. Its easy to configure using the builder pattern NimbusJWTDecoder

Just add it as a bean and spring will automatically pick it up and inject it into the built in jwt filter.

@Bean
public JwtDecoder jwtDecoder() {
    // Use builder functions to configure how the JWT should be validated.
    return NimbusJwtDecoder.withPublicKey(this.key).build();
}

If you wish to configure scopes and map these as roles in your application you can just add a JwtAuthenticationConverter that will take the scopes and map them to roles with the ROLE_ prefix. If you don't add a converter your scopes will have the SCOPE_ prefix.

@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
    JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
    grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");

    JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
    return jwtAuthenticationConverter;
}

Please read up on how JWTs in spring security work, there is an entire chapter on how to simple and easy implement the handling of JWTs in spring security.

Spring security JWT