首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用spring-authorization-server在JWT中创建自定义声明

如何使用spring-authorization-server在JWT中创建自定义声明
EN

Stack Overflow用户
提问于 2021-01-12 00:21:54
回答 2查看 975关注 0票数 5

我正在基于实验性的Spring项目Spring Authorization Server构建一个OAuth2授权服务器

我的用例非常简单,从数据库中获取用户,然后根据用户的一些属性,在生成的JWT中设置一些自定义声明。我还没有找到使用Spring Authorization Server实现此目的的方法,唯一可行的方法是将jwtCustomizer对象作为Spring bean定义的一部分进行注入:

代码语言:javascript
复制
  @Bean
  public JwtEncoder jwtEncoder(CryptoKeySource keySource) {
    NimbusJwsEncoder jwtEncoder = new NimbusJwsEncoder(keySource);
    jwtEncoder.setJwtCustomizer((headersBuilder, claimsBuilder) -> {
      // Inject some headers and claims...
    });
    return jwtEncoder;
  }

这显然不能让我访问用户信息,因此我不能在这一点上设置我需要的声明。有人设法解决了这个问题吗?

EN

回答 2

Stack Overflow用户

发布于 2021-04-29 11:05:51

The solution for this is in a test of the library

代码语言:javascript
复制
    @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);
            }
        };
    }
票数 2
EN

Stack Overflow用户

发布于 2021-01-15 19:51:30

你可以尝试下面的方法。虽然它是Kotlin代码,而不是Java,但方法应该是明确的:

代码语言:javascript
复制
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:

代码语言:javascript
复制
@Bean
fun userTokenEnhancer(): TokenEnhancer {
    return UserTokenEnhancer()
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65670673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档