我正在基于实验性的Spring项目Spring Authorization Server构建一个OAuth2授权服务器
我的用例非常简单,从数据库中获取用户,然后根据用户的一些属性,在生成的JWT中设置一些自定义声明。我还没有找到使用Spring Authorization Server实现此目的的方法,唯一可行的方法是将jwtCustomizer对象作为Spring bean定义的一部分进行注入:
@Bean
public JwtEncoder jwtEncoder(CryptoKeySource keySource) {
NimbusJwsEncoder jwtEncoder = new NimbusJwsEncoder(keySource);
jwtEncoder.setJwtCustomizer((headersBuilder, claimsBuilder) -> {
// Inject some headers and claims...
});
return jwtEncoder;
}这显然不能让我访问用户信息,因此我不能在这一点上设置我需要的声明。有人设法解决了这个问题吗?
发布于 2021-04-29 11:05:51
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);
}
};
}发布于 2021-01-15 19:51:30
你可以尝试下面的方法。虽然它是Kotlin代码,而不是Java,但方法应该是明确的:
import org.springframework.security.oauth2.provider.token.TokenEnhancer
class UserTokenEnhancer : TokenEnhancer {
override fun enhance(accessToken: OAuth2AccessToken,
authentication: OAuth2Authentication): OAuth2AccessToken {
val username = authentication.userAuthentication.name
val additionalInfo = mapOf( /* populate with some data for given username */ )
(accessToken as DefaultOAuth2AccessToken).additionalInformation = additionalInfo
return accessToken
}
}然后只需注册bean:
@Bean
fun userTokenEnhancer(): TokenEnhancer {
return UserTokenEnhancer()
}https://stackoverflow.com/questions/65670673
复制相似问题