问题描述
我正在基于实验性的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);
}
};
}