Search code examples
springspring-securityspring-oauth2

OAuth 2 resource server doesn't put claims into authorities


I'm getting an access token from a Spring Authorization Server that has claim "roles". Then i try to put roles in authorities.

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, JwtAuthenticationConverter jwtAuthenticationConverter) throws Exception {
        http
                .authorizeHttpRequests(authorize ->
                        authorize
                                .anyRequest().authenticated()
                )
                .cors(Customizer.withDefaults())
                .oauth2Login(Customizer.withDefaults())
                .oauth2Client(Customizer.withDefaults())
                .oauth2ResourceServer(oauth2
                        -> oauth2.jwt(jwt->jwt.jwtAuthenticationConverter(jwtAuthenticationConverter)));

        return http.build();
    }
    @Bean
    public JwtAuthenticationConverter jwtAuthenticationConverter(){
        JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        grantedAuthoritiesConverter.setAuthoritiesClaimName("roles");

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

Access token: enter image description here

But when i try to check the authority is present with @PreAuthorize("hasAuthority('USER')") i receive "Access denied".

I want to have roles in authorities, but I only have scope in it. For example, @PreAuthorize("hasAuthority('SCOPE_SOMETHING')") works perfect.


Solution

  • The main problem was that I put the claims in the JwtAuthenticationToken, but my OAuth2 client and resource server were in the same app with OIDC authorization and so the problem was solved after I put and view the claims from the OAuth2AuthenticationToken