OAUTH2 custom JwtGrantedAuthoritiesConverter

671 Views Asked by At

How to create a custom JwtGrantedAuthoritiesConverter to get roles from a specific claim.

I am using Spring Security 6 and an authorization server to validate opaque access tokens. I would like to populate authorities based on the "access" field from the introspection response.

Introspection response:

{
    "username": "user_test",
    "scope": "STANDARD",
    "access": [
       "CUSTOM_ROLE_111",
       "CUSTOM_ROLE_222",
       "CUSTOM_ROLE_333",
       "CUSTOM_ROLE_444",
    ],
    "name": "acessor",
    "active": true,
    "loginType": "PASSWORD",
    "refreshToken": "$2b$10$s...",
    "iat": 1692016676,
    "exp": 1692103076
}

I tried:

 @Bean
  public Converter<Jwt, AbstractAuthenticationToken> jwtAuthenticationConverter() {
    return jwt -> {
      List<GrantedAuthority> authorities = new ArrayList<>();
      List<String> accessScopes = jwt.getClaimAsStringList("access");

      for (String scope : accessScopes) {
        authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
      }

      return new JwtAuthenticationToken(jwt, authorities);
    };
  }

and then:

@Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(authorize -> authorize
            .anyRequest().authenticated()
        )
        .oauth2ResourceServer(oauth -> 
             oauth.opaqueToken(opaqueTokenConfigurer -> 
               opaqueTokenConfigurer.introspector(opaqueTokenIntrospector())));
    return http.build();
  }

Bu didn't work at all. Several BeanCreationException happens

Any idea how to work around it?

Basically, As I understood so far, by creating acustom customJwtGrantedAuthoritiesConvert also need to expose a Bean for JwtDecoder. From documentation to Exposing a JwtDecoder @Bean I'll need the jwk. Since I am using introspection I have not the jwk.

My logs: 2023-08-15T15:42:09.555+03:00 ERROR 3828 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :


APPLICATION FAILED TO START


Description:

Parameter 0 of method setFilterChains in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' that could not be found.

reference: https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html

1

There are 1 best solutions below

0
Siva Kumar On

You need to declare JWTDecoder bean as well.

Something like below..

@Bean
public JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withIssuerLocation(TOKEN_ISSUE_URL).build();
}

Also you can create JwtDecoder bean using JwkURI, SecretKey and public key.