Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Keycloak - How to get a list of roles assigned to a user?

Tags:

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?

like image 316
Charlie Avatar asked Jul 31 '17 04:07

Charlie


People also ask

How do I get user roles from a Keycloak?

A user would have to be authenticated before seeing some application content. After successful authentication, access token would be given to client (can be application gateway or ui application) and then role can be extracted from it and used. How the role can be extracted from the JWT Access token?

What is client role in Keycloak?

Keycloak roles are defined in a dedicated namespace so that all users with the same roles have identical permissions in that namespace. In other words, realm-level roles are a global namespace for a given realm, while client roles are namespaces intended for specific applications.


1 Answers

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();
like image 151
ravthiru Avatar answered Oct 11 '22 14:10

ravthiru