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

只谈情不闲聊 提交于 2019-12-07 16:36:31

问题


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?


回答1:


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();


来源:https://stackoverflow.com/questions/45407568/spring-boot-keycloak-how-to-get-a-list-of-roles-assigned-to-a-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!