0

OAuth2 を使用して保護されたスプリング ブート REST API があります。私の認証サーバーとリソース サーバーは 2 つのアプリケーションです。すべての REST API セキュリティは、REST クライアントで適切に動作します。次に、セキュリティ テスト ケースを作成する必要があります。次のコードを使用してアクセス トークンを生成します。一部のエンド ポイントでは、REST メソッド内にクレームを手動で追加する必要があります。プログラムは有効なアクセス トークンを与えられましたが、このトークンに含まれていないと主張しています。

private String generateToken(String... authorities) {

    JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
    converter.setSigningKey("123");

    tokenService = new DefaultTokenServices();

    JwtTokenStore jwtTokenStore = new JwtTokenStore(converter);
    tokenService.setTokenStore(jwtTokenStore);

    tokenService.setTokenEnhancer(converter);

    Collection<GrantedAuthority> grantAuthorities = new ArrayList<>();

    if (authorities != null) {
        for (String authority: authorities) {
            grantAuthorities.add(new SimpleGrantedAuthority(authority));
        }
    }

    Set<String> resourceIds = Collections.emptySet();
    Set<String> scopes = Collections.emptySet();

    Map<String, String> requestParameters = Collections.emptyMap();
    boolean approved = true;
    String redirectUrl = null;
    Set<String> responseTypes = Collections.emptySet();
    Map<String, Serializable> extensionProperties = Collections.emptyMap();

    OAuth2Request oAuth2Request = new OAuth2Request(requestParameters, "web-client", grantAuthorities,
            approved, scopes, resourceIds, redirectUrl, responseTypes, extensionProperties);

    User userPrincipal = new User("user", "", true, true,
            true, true, grantAuthorities);
    UsernamePasswordAuthenticationToken authenticationToken =
            new UsernamePasswordAuthenticationToken(userPrincipal, null, grantAuthorities);

    OAuth2Authentication auth = new OAuth2Authentication(oAuth2Request, authenticationToken);

    OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);

    Map<String, Object> claims = new HashMap<>();

    List<Long> tenantIds = new ArrayList<>();
    tenantIds.add(1L);

    claims.put("role", 1L);
    claims.put("tenants", tenantIds);

    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(claims);

    return accessToken.getValue();

}

このトークンにクレームを追加する方法。

4

1 に答える 1