Внедрить TokenEnhancer для OAuth2 + JWT - PullRequest
1 голос
/ 14 июля 2020

Я пытаюсь реализовать TokenEnhancer для OAuth2 + JWT, используя этот код:

public class CustomTokenEnhancer implements TokenEnhancer {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        final Map<String, Object> additionalInfo = new HashMap<>();
        additionalInfo.put("organization", authentication.getName() + " test");
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}

Вы знаете, как я могу добавить роль пользователя и добавить ее в полезную нагрузку токена?

1 Ответ

2 голосов
/ 15 июля 2020

Вы не сможете сделать это, используя этот подход, вам нужно реализовать свое собственное поведение для JwtAccessTokenConverter. Вы можете увидеть пример в следующем коде:

public class CustomAccessTokenConverter extends JwtAccessTokenConverter {

  private static final String AUTHORITIES = "authorities";
  private static final String SCOPE = "scope";
  private static final String USERNAME = "username";
  private static final String ADDITIONAL_INFO = "additionalInfo";

  public CustomAccessTokenConverter() {
    super();
  }

  @Override
  public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    OAuth2AccessToken result = super.enhance(accessToken, authentication);
    result.getAdditionalInformation().putAll(getAdditionalInformation(authentication));
    return result;
  }


  @Override
  public Map<String, ?> convertAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    Map<String, Object> defaultInformation = (Map<String, Object>) super.convertAccessToken(token, authentication);
    return this.isRefreshToken(token) ? getRefreshTokenInformation(defaultInformation)
                                      : getAccessTokenInformation(defaultInformation);
  }

  /**
   * Filter the data included in the JWT access token
   */
  private Map<String, ?> getAccessTokenInformation(Map<String, Object> sourceInformation) {
    Map<String, Object> accessTokenInformation = new HashMap<>(sourceInformation);
    accessTokenInformation.keySet().removeIf(k -> asList(SCOPE).contains(k));
    return accessTokenInformation;
  }

  /**
   * Filter the data included in the JWT refresh token
   */
  private Map<String, ?> getRefreshTokenInformation(Map<String, Object> sourceInformation) {
    Map<String, Object> refreshTokenInformation = new HashMap<>(sourceInformation);
    refreshTokenInformation.keySet().removeIf(k -> asList(AUTHORITIES, SCOPE).contains(k));
    return refreshTokenInformation;
  }

  /**
   * Include an specific section with extra information in the returned {@link OAuth2AccessToken}
   */
  private Map<String, Object> getAdditionalInformation(OAuth2Authentication authentication) {
    Map<String, Object> authenticationAdditionalInformation = Map.ofEntries(
            entry(USERNAME, authentication.getUserAuthentication().getName()),
            entry(AUTHORITIES,
                    authentication.getAuthorities().stream()
                            .map(GrantedAuthority::getAuthority)
                            .collect(toSet()))
    );
    return Map.of(ADDITIONAL_INFO, authenticationAdditionalInformation);
  }

}

Вы можете увидеть этот код и остальную часть микросервиса здесь .

С другой стороны, в по следующей ссылке вы сможете увидеть руководство с полной интеграцией с: JWT + Oauth2

...