Сгенерируйте маркер доступа OAuth2 с дополнительными утверждениями для теста JUnit - PullRequest
0 голосов
/ 03 января 2019

REST API для весенней загрузки защищен с использованием OAuth2.Мой сервер аутентификации и сервер ресурсов - это два приложения.Вся безопасность 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();

}

Как добавить претензии к этому токену.

1 Ответ

0 голосов
/ 03 января 2019

Наконец-то нашел решение.Добавьте TokenEnhancerChain к коду

Ниже приведен окончательный код

private String generateToken(String... authorities) {

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

    tokenService = new DefaultTokenServices();

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

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

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

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

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

    OAuth2AccessToken accessToken = tokenService.createAccessToken(auth);

    TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
    tokenEnhancerChain.setTokenEnhancers(
            Arrays.asList(new CustomTokenEnhancer(), converter));

    accessToken = tokenEnhancerChain.enhance(accessToken, auth);

    return accessToken.getValue();

}

ВАЖНО: Добавьте JwtAccessTokenConverter в качестве конечного элемента списка расширений токенов

Ниже приведенКласс CustomTokenEnhancer.

public class CustomTokenEnhancer extends JwtAccessTokenConverter {

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Map<String, Object> claims = new HashMap<>();

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

        claims.put("role", 1L);
        claims.put("tenants", tenantIds);
        claims.put("userId", "admin@abc.com");

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

        return accessToken;

    }
}
...