【问题标题】:How to create custom claims in JWT using spring-authorization-server如何使用 spring-authorization-server 在 JWT 中创建自定义声明
【发布时间】:2021-04-16 14:54:00
【问题描述】:

我正在基于实验性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;
  }

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

【问题讨论】:

  • 您可以在构建 UserDetails 对象时设置声明,在您实现的 Spring 的 UserDetailsService::loadUserByUsername
  • 不,你不能,我试过了。您可以在 UserDetailsService::loadUserByName 中设置角色和权限,但您设置的角色和权限都不会在 JWT 中结束

标签: spring spring-boot spring-security spring-security-oauth2


【解决方案1】:

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);
            }
        };
    }

【讨论】:

    【解决方案2】:

    您可以尝试以下方式。虽然是 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()
    }
    

    【讨论】:

    • TokenEnhancer 在 Spring Security 5 中不可用,这似乎是 spring-authorization-server 项目所基于的。所以不,这个解决方案不适用于我的具体情况。
    猜你喜欢
    • 1970-01-01
    • 2018-07-05
    • 2019-10-17
    • 2022-12-30
    • 2019-02-26
    • 2015-03-18
    • 2020-03-15
    • 2016-01-06
    • 2017-12-27
    相关资源
    最近更新 更多