【问题标题】:Spring boot keycloak integration comes in role null in @preauthorizeSpring boot keycloak 集成在 @preauthorize 中的角色为 null
【发布时间】:2022-07-24 22:15:39
【问题描述】:

我正在尝试使用 keycloak 执行 授权 操作。

我的安全配置类工作正常,我通过 jwt 令牌成功创建了身份验证并执行了必要的角色映射。这通过安全上下文持有者清晰可见。

我使用的是preauthorize注解,因为里面的authorities为null,没有提供授权,我得到403。

我还是不明白怎么可能,你能帮忙吗?

【问题讨论】:

    标签: spring-boot spring-security keycloak


    【解决方案1】:

    经过长期的奋斗,我找到了解决办法。

    @Override
    protected KeycloakAuthenticationProvider keycloakAuthenticationProvider() {
        return new KeycloakAuthenticationProvider() {
    
            @Override
            public Authentication authenticate(Authentication authentication) throws AuthenticationException {
                KeycloakAuthenticationToken token = (KeycloakAuthenticationToken) authentication;
                List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    
                for (String role : ((KeycloakPrincipal) token.getPrincipal()).getKeycloakSecurityContext().getToken().getRealmAccess().getRoles()) {
                    grantedAuthorities.add(new KeycloakRole(role));
                }
    
                return new KeycloakAuthenticationToken(token.getAccount(), token.isInteractive(), new SimpleAuthorityMapper().mapAuthorities(grantedAuthorities));
            }
    
        };
    }
    

    我们可以通过在 Security config 类中使用以下方法将角色设置为 KeycloakAuthenticationToken 来达到解决方案。

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,你的选项工作正常,但没有其他简单的选项来解决它?,抛出配置或其他简单的方法?

      【讨论】:

        猜你喜欢
        • 2020-01-11
        • 2021-08-18
        • 2019-04-28
        • 1970-01-01
        • 2017-09-12
        • 1970-01-01
        • 1970-01-01
        • 2022-11-17
        • 1970-01-01
        相关资源
        最近更新 更多