Search code examples
javaspring-bootjwtoauth2resourceserveroauth-2.1

How to get scope and roles in Oauth2/2.1 spring boot resource server?


How to get scope and roles in Oauth2/2.1 spring boot resource server?

Authentication authentication = getAuthentication();
System.out.println(authentication.getAuthorities());

Authorities returns only scope.

Here is my token introspect

{
    "active": true,
    "sub": "0f370b1e-e3a9-4ee3-a8a3-21bbb3437c16",
    "aud": [
        "1"
    ],
    "nbf": 1679019352,
    "scope": "read",
    "roles": [
        "user"
    ],
    "iss": "http://3.6.239.198:9000",
    "exp": 1679022352,
    "iat": 1679019352,
    "client_id": "1",
    "token_type": "Bearer"
}

How to retrieve role in the resource server?


Solution

  • Created CustomAuthenticationConverter to replace scope with roles

    @Configuration
    @EnableWebSecurity
    public class OAuth2ResourceServerSecurityConfiguration {
        
        @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}")
        private String authServerBaseUrl;
        
        interface Jwt2AuthoritiesConverter extends Converter<Jwt, Collection<? extends GrantedAuthority>> {
        }
    
        List<String> publicApis = List.of("/login", "/rest/**", "/token", 
                 "/swagger-ui/**", "/v3/api-docs/**", "/vendor/**", "/favicon.ico");
         
        @Bean
        public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {    
            http.anonymous().disable();       
            http.cors().and().authorizeHttpRequests(authorize -> authorize
                    .requestMatchers(publicApis.stream()
                            .map(AntPathRequestMatcher::new)
                            .toArray(RequestMatcher[]::new)).permitAll()
                
                    .anyRequest().authenticated()).csrf().disable();
                
            http.oauth2ResourceServer(oauth2 -> oauth2
                    .jwt(jwt -> jwt
                            .jwtAuthenticationConverter(new CustomAuthenticationConverter())
                        )
                    );
        
                  
            return http.build();
        }
      
        static class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
            public AbstractAuthenticationToken convert(Jwt jwt) {
                Collection<String> authorities = jwt.getClaimAsStringList("roles");
                Collection<GrantedAuthority> grantedAuthorities = authorities.stream()
                        .map(SimpleGrantedAuthority::new)
                        .collect(Collectors.toList());
                return new JwtAuthenticationToken(jwt, grantedAuthorities);
            }
        }
    }
    

    To Get roles:

    Authentication authentication = getAuthentication();
    authentication.getAuthorities()
    

    Refer :-

    Authorization server -> https://github.com/m-thirumal/oauth-authorization-server/

    Resource server -> https://github.com/m-thirumal/oauth-resource-server https://github.com/m-thirumal/oauth-resource-server