Spring Security Spring oauth2授权服务器在令牌中添加角色用户

apeeds0o  于 2022-12-13  发布在  Spring
关注(0)|答案(2)|浏览(157)

我使用spring-security-oauth2-authorization-server(v.0.2.0)来实现我的授权服务器。我希望用户角色在令牌中,可以添加它们吗?
谢谢

t3psigkw

t3psigkw1#

我通过添加以下bean解决了这个问题

@Bean
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
    return context -> {
        if (context.getTokenType() == OAuth2TokenType.ACCESS_TOKEN.getValue()) {
            Authentication principal = context.getPrincipal();
            Set<String> authorities = principal.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toSet());
            context.getClaims().claim("user-authorities", authorities);
        }
    };
}
ruoxqz4g

ruoxqz4g2#

它应该是'=='检查,ACCESS_TOKEN不是值。

@Bean
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
    return context -> {
        if (context.getTokenType() == OAuth2TokenType.ACCESS_TOKEN) {
            Authentication principal = context.getPrincipal();
            Set<String> authorities = principal.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toSet());
            context.getClaims().claim("user-authorities", authorities);
        }
    };
}

相关问题