将用户数据添加到 spring 安全 OAUth2 的 JWT 负载

Adding User data to the JWT payload for spring security OAUth2

我使用 JWT 令牌的 spring 安全 OAuth2 已经有一段时间了,但现在我需要向 JWT 令牌添加 2 个用户定义的值。

所以当我向请求添加一组额外的参数时 /oauth/token?grant_type=client_credentials&user_value=1234567890.

上面的user_value是为了演示目的。我可以将它一直追踪到我的 CustomTokenEnhancer 中(我连接它是为了一直传递此信息)。通过传递到我的 CustomTokenEnhancer 的 OAuth2Authentication 身份验证,所有请求参数都是可见的。

现在我可以将此信息添加到我看到的作为令牌请求的一部分返回给我的附加信息中。见下文。

{
   "access_token":"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicGhpLWFwaSJdLCJzY29wZSI6WyJyZWFkIiwid3JpdGUiXSwib3JnYW5pemF0aW9uIjoicGhpLXVzZXJtZ3RuIiwidXNlcl90b2tlbiI6IjEyMzQ1Njc4OTAiLCJleHAiOjE0ODczNjc2NzEsImF1dGhvcml0aWVzIjpbIlJPTEVfQ0xJRU5UIl0sImp0aSI6IjFlZDMzZTAxLTc1ZGUtNDNjZC1hMzk2LTFkMzk2N2Y1NDQ5OCIsImNsaWVudF9pZCI6InBoaS11c2VyIn0.p628BNaaGljypEcGXZMkstNeTN-221qzzNQQ0npxDLTszWaXkgXqsBnBbKf9XMEtWTeCQkIszC9ne1Ei2X5IWTskhLT9Rko-8K7Jq-mXUc6HJZW-3tGV5rRer8Eyyw1wysW9Jiyp7sPkN-TIx12A70f_LHm6PrRR4ECppHWADs-2DvYA30p8omT1_RTt2WlqC40mopUN2TBPkb1WulVpOUEpcP358Ox8oVP8VQRSkLGZKB_b0KZAK9KGjLg6WNh8RghZaBuYuJQpITe_0XEBs_JfwrHhcK1IGaoYwSS7IGp3Cima9OMljdzayDKRqlfSl3WhaBuFmD1S37p-OVQL0A",
   "token_type":"bearer",
   "expires_in":8967,
   "scope":"read write",
   "user_value":"1234567890",
   "jti":"1ed33e01-75de-43cd-a396-1d3967f54498"
}

但我不希望这些值以这种方式可见。我希望将它们添加到加密令牌中。

我花了一些时间查看,但不清楚我是如何添加的。这应该是可能的,不是吗?

我在用户详细信息服务(不是令牌增强器)的帮助下做了类似的事情,将值作为授予的权限传递。在客户端,我编写了一个提取器来检索由 spring 注入的委托人的值作为 OAuth2Authentication 类型。以下代码是在 Scala 中编写的,但您可以轻松适应 Java:

/**
  * Mix-in to implicitly extract entity or identity from the principal.
  */
trait AuthorityExtractor {

  def _contextName(implicit principal: OAuth2Authentication) = id(principal, "CONTEXT_")

  def _entityId(implicit principal: OAuth2Authentication) = id(principal, "ENTITY_ID_")

  def _userId(implicit principal: OAuth2Authentication) = id(principal, "USER_ID_")

  def _identityId(implicit principal: OAuth2Authentication) = id(principal, "SELF_ID_")

  private def id(principal: OAuth2Authentication, prefix: String) = {
    import collection.JavaConversions._
    principal
      .getAuthorities
      .filter(_.toString.startsWith(prefix))
      .map(_.toString.substring(prefix.length))
      .headOption.getOrElse("")
  }

}

在您自己的 TokenEnhancer 中,您必须再次对其进行编码:

@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    // Generate additional Information [...]


    // Write it to the token
    ((DefaultOAuth2AccessToken)accessToken).setAdditionalInformation(addInfo);

    // Encode Token to JWT
    String encoded = super.encode(accessToken, authentication);

    // Set JWT as value of the token
    ((DefaultOAuth2AccessToken) accessToken).setValue(encoded);

    return accessToken;
}

你可以用 JwtHelper 方法解决这个问题,但我只是扩展了 JwtAccessTokenConverter,所以我可以只使用编码和解码。

在实例化您的令牌增强器时,您必须添加密钥库信息:

private CustomTokenEnhancer jwtCustomEnhancer() {
    KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource("jwt.jks"), "***".toCharArray());
    CustomTokenEnhancer converter = new CustomTokenEnhancer();
    converter.setKeyPair(keyStoreKeyFactory.getKeyPair("jwt"));

    return converter;
}

我这样扩展 JwtAccessTokenConverter class:

public class FooJwtAccessTokenConverter extends JwtAccessTokenConverter {
  @Override
  public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
     DefaultOAuth2AccessToken fooAccessToken = new DefaultOAuth2AccessToken(accessToken);
     fooAccessToken.getAdditionalInformation().put("foo_property", "foo");
     return super.enhance(scaAccessToken, authentication);
  }

在我的 AuthotizationServerConfig 中,我创建了这个:

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    endpoints
            .tokenStore(tokenStore())
            .accessTokenConverter(accessTokenConverter())
            .authenticationManager(authenticationManager);
}

@Bean
public TokenStore tokenStore() {
    return new JwtTokenStore(accessTokenConverter());
}

@Bean
public JwtAccessTokenConverter accessTokenConverter() {
    ScaJwtAccessTokenConverter accessTokenConverter = new ScaJwtAccessTokenConverter();
    accessTokenConverter.setSigningKey("familia-mgpe"); // Parte da string de validação do token JWT.
    return accessTokenConverter;
}