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

Nic*_*lis 9 spring spring-security spring-boot spring-security-oauth2

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

我的用例非常简单,从数据库中获取用户,并根据用户的某些属性,在正在生成的 JWT 中设置一些自定义声明。我还没有找到使用 Spring Authorization Server 的方法,我能解决的唯一方法是注入一个jwtCustomizer对象作为JwtEncoderbean 定义的一部分:

  @Bean
  public JwtEncoder jwtEncoder(CryptoKeySource keySource) {
    NimbusJwsEncoder jwtEncoder = new NimbusJwsEncoder(keySource);
    jwtEncoder.setJwtCustomizer((headersBuilder, claimsBuilder) -> {
      // Inject some headers and claims...
    });
    return jwtEncoder;
  }
Run Code Online (Sandbox Code Playgroud)

这显然不允许我访问用户信息,因此我目前无法设置我需要的声明。有人设法解决这个问题吗?

小智 19

解决方案是在库的测试中

    @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);
            }
        };
    }
Run Code Online (Sandbox Code Playgroud)


Nik*_*nko 0

你可以尝试下面的方法。虽然它是 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
    }
}
Run Code Online (Sandbox Code Playgroud)

然后只需注册bean:

@Bean
fun userTokenEnhancer(): TokenEnhancer {
    return UserTokenEnhancer()
}
Run Code Online (Sandbox Code Playgroud)

  • TokenEnhancer 在 Spring Security 5 中不可用,这似乎是 spring-authorization-server 项目所基于的。所以不,这个解决方案不适用于我的具体情况。 (5认同)