6

I am trying to get a list of roles assigned to a particular user from a Spring Boot application secured with keycloak.

I have declared an AccessToken bean in the KeycloakWebSecurityConfigurerAdapter configuration class as follows:

    @Configuration
    @EnableWebSecurity
    @ComponentScan(basePackageClasses = KeycloakSecurityComponents.class)
    public class KeycloakSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {

//other config code

        @Bean
        @Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
        public AccessToken accessToken() {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
            return ((KeycloakSecurityContext) ((KeycloakAuthenticationToken) request.getUserPrincipal()).getCredentials()).getToken();
        }

    }

Now I can autowire the AccessToken in the controller and I am able to get the information like ID and username but how do I get the list of roles assigned to the user using the AccessToken?

Charlie
  • 3,113
  • 3
  • 38
  • 60

1 Answers1

4

for resource role mapping use

AccessToken.Access access = accessToken.getResourceAccess(clientId);
     Set<String> roles = access.getRoles();

for realm role mappings use

AccessToken.Access access = accessToken.getRealmAccess();
 Set<String> roles = access.getRoles();
ravthiru
  • 8,878
  • 2
  • 43
  • 52
  • Is it possible to have a full example of SecurityConfig & another class e.g. controller where this AccessToken is used? – Saurabhcdt Sep 19 '19 at 12:38