如何在JWT中使用SpringAUTORIZATION-SERVER创建定制声明 [英] How to create custom claims in JWT using spring-authorization-server
本文介绍了如何在JWT中使用SpringAUTORIZATION-SERVER创建定制声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在基于实验性的Spring项目Spring Authorization Server
构建一个OAuth2授权服务器我的用例非常简单,从一个数据库中获取用户,并根据用户的一些属性,在生成的JWT中设置一些定制声明。
我还没有找到使用Spring Authorization Server这样做的方法,唯一可以解决的方法是将jwtCustomizer
对象作为JwtEncoder
Bean定义的一部分注入:
@Bean
public JwtEncoder jwtEncoder(CryptoKeySource keySource) {
NimbusJwsEncoder jwtEncoder = new NimbusJwsEncoder(keySource);
jwtEncoder.setJwtCustomizer((headersBuilder, claimsBuilder) -> {
// Inject some headers and claims...
});
return jwtEncoder;
}
这显然不能让我访问用户信息,因此我现在无法设置我需要的声明。 有人设法解决了这个问题吗?
推荐答案
The solution for this is in a test of the library
@Bean
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
return context -> {
if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
Authentication principal = context.getPrincipal();
Set<String> authorities = principal.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toSet());
context.getClaims().claim(AUTHORITIES_CLAIM, authorities);
}
};
}
这篇关于如何在JWT中使用SpringAUTORIZATION-SERVER创建定制声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文