Spring Boot Keycloak-如何获取分配给用户的角色列表? [英] Spring Boot Keycloak - How to get a list of roles assigned to a user?

查看:803
本文介绍了Spring Boot Keycloak-如何获取分配给用户的角色列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正试图从使用keycloak保护的Spring Boot应用程序中获取分配给特定用户的角色列表.

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

我已经在KeycloakWebSecurityConfigurerAdapter配置类中声明了一个AccessToken bean,如下所示:

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

    }

现在,我可以在控制器中自动连接AccessToken了,我可以获取ID和用户名之类的信息,但是如何获取使用AccessToken分配给用户的角色列表?

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?

推荐答案

用于资源角色映射

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

用于领域角色映射

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

这篇关于Spring Boot Keycloak-如何获取分配给用户的角色列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆