【问题标题】:Spring Boot Keycloak - How to get a list of roles assigned to a user?Spring Boot Keycloak - 如何获取分配给用户的角色列表?
【发布时间】:2018-01-06 12:50:05
【问题描述】:

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

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

    @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 获取分配给用户的角色列表?

【问题讨论】:

    标签: java spring spring-boot spring-data-rest keycloak


    【解决方案1】:

    用于资源角色映射使用

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

    对于领域角色映射使用

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

    【讨论】:

    • 是否有可能有一个完整的 SecurityConfig 示例和另一个类,例如使用此 AccessToken 的控制器?
    猜你喜欢
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 2021-01-03
    • 2023-02-14
    • 2021-08-18
    • 2019-06-04
    • 2017-11-12
    • 1970-01-01
    相关资源
    最近更新 更多