Example usage for org.springframework.security.oauth2.provider TokenRequest TokenRequest

List of usage examples for org.springframework.security.oauth2.provider TokenRequest TokenRequest

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.provider TokenRequest TokenRequest.

Prototype

public TokenRequest(Map<String, String> requestParameters, String clientId, Collection<String> scope,
        String grantType) 

Source Link

Document

Full constructor.

Usage

From source file:org.mitre.oauth2.service.impl.TestDefaultOAuth2ProviderTokenService.java

/**
 * Set up a mock authentication and mock client to work with.
 *///from  w ww . ja v a  2s  .c o  m
@Before
public void prepare() {
    Mockito.reset(tokenRepository, authenticationHolderRepository, clientDetailsService, tokenEnhancer);

    authentication = Mockito.mock(OAuth2Authentication.class);
    OAuth2Request clientAuth = new OAuth2Request(null, clientId, null, true, scope, null, null, null, null);
    Mockito.when(authentication.getOAuth2Request()).thenReturn(clientAuth);

    client = Mockito.mock(ClientDetailsEntity.class);
    Mockito.when(client.getClientId()).thenReturn(clientId);
    Mockito.when(clientDetailsService.loadClientByClientId(clientId)).thenReturn(client);
    Mockito.when(client.isReuseRefreshToken()).thenReturn(true);

    // by default in tests, allow refresh tokens
    Mockito.when(client.isAllowRefresh()).thenReturn(true);

    // by default, clear access tokens on refresh
    Mockito.when(client.isClearAccessTokensOnRefresh()).thenReturn(true);

    badClient = Mockito.mock(ClientDetailsEntity.class);
    Mockito.when(badClient.getClientId()).thenReturn(badClientId);
    Mockito.when(clientDetailsService.loadClientByClientId(badClientId)).thenReturn(badClient);

    refreshToken = Mockito.mock(OAuth2RefreshTokenEntity.class);
    Mockito.when(tokenRepository.getRefreshTokenByValue(refreshTokenValue)).thenReturn(refreshToken);
    Mockito.when(refreshToken.getClient()).thenReturn(client);
    Mockito.when(refreshToken.isExpired()).thenReturn(false);

    tokenRequest = new TokenRequest(null, clientId, null, null);

    storedAuthentication = authentication;
    storedAuthRequest = clientAuth;
    storedAuthHolder = Mockito.mock(AuthenticationHolderEntity.class);
    storedScope = Sets.newHashSet(scope);

    Mockito.when(refreshToken.getAuthenticationHolder()).thenReturn(storedAuthHolder);
    Mockito.when(storedAuthHolder.getAuthentication()).thenReturn(storedAuthentication);
    Mockito.when(storedAuthentication.getOAuth2Request()).thenReturn(storedAuthRequest);

    Mockito.when(authenticationHolderRepository.save(Matchers.any(AuthenticationHolderEntity.class)))
            .thenReturn(storedAuthHolder);

    Mockito.when(scopeService.fromStrings(Matchers.anySet())).thenAnswer(new Answer<Set<SystemScope>>() {
        @Override
        public Set<SystemScope> answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            Set<String> input = (Set<String>) args[0];
            Set<SystemScope> output = new HashSet<>();
            for (String scope : input) {
                output.add(new SystemScope(scope));
            }
            return output;
        }
    });

    Mockito.when(scopeService.toStrings(Matchers.anySet())).thenAnswer(new Answer<Set<String>>() {
        @Override
        public Set<String> answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            Set<SystemScope> input = (Set<SystemScope>) args[0];
            Set<String> output = new HashSet<>();
            for (SystemScope scope : input) {
                output.add(scope.getValue());
            }
            return output;
        }
    });

    // we're not testing restricted or reserved scopes here, just pass through
    Mockito.when(scopeService.removeReservedScopes(Matchers.anySet()))
            .then(AdditionalAnswers.returnsFirstArg());
    Mockito.when(scopeService.removeRestrictedAndReservedScopes(Matchers.anySet()))
            .then(AdditionalAnswers.returnsFirstArg());

    Mockito.when(tokenEnhancer.enhance(Matchers.any(OAuth2AccessTokenEntity.class),
            Matchers.any(OAuth2Authentication.class))).thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
                @Override
                public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args = invocation.getArguments();
                    return (OAuth2AccessTokenEntity) args[0];
                }
            });

    Mockito.when(tokenRepository.saveAccessToken(Matchers.any(OAuth2AccessTokenEntity.class)))
            .thenAnswer(new Answer<OAuth2AccessTokenEntity>() {
                @Override
                public OAuth2AccessTokenEntity answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args = invocation.getArguments();
                    return (OAuth2AccessTokenEntity) args[0];
                }

            });

    Mockito.when(tokenRepository.saveRefreshToken(Matchers.any(OAuth2RefreshTokenEntity.class)))
            .thenAnswer(new Answer<OAuth2RefreshTokenEntity>() {
                @Override
                public OAuth2RefreshTokenEntity answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args = invocation.getArguments();
                    return (OAuth2RefreshTokenEntity) args[0];
                }
            });

}

From source file:it.smartcommunitylab.aac.apimanager.APIProviderManager.java

/**
 * /*from  www.java2 s  .  c o  m*/
 * @return
 * @throws Exception
 */
@Transactional(isolation = Isolation.SERIALIZABLE)
public String createToken() throws Exception {
    Map<String, String> requestParameters = new HashMap<>();
    String apiManagerName = getAPIManagerName();

    Long userId = userManager.getUser().getId();
    if (apiManagerName == null) {
        return null;
    }
    requestParameters.put("username", apiManagerName);
    requestParameters.put("password", "");

    // USER
    org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
            userId.toString(), "", new ArrayList<GrantedAuthority>());

    ClientDetails clientDetails = getAPIMgmtClient();
    TokenRequest tokenRequest = new TokenRequest(requestParameters, clientDetails.getClientId(), scopes(),
            "password");
    OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
    Collection<? extends GrantedAuthority> list = authorities();
    OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request,
            new UsernamePasswordAuthenticationToken(user, "", list));
    OAuth2AccessToken accessToken = tokenService.createAccessToken(oAuth2Authentication);
    return accessToken.getValue();
}

From source file:it.smartcommunitylab.aac.apimanager.APIProviderManager.java

/**
 * /*from   ww w  .j  a va  2 s. c om*/
 * @return
 * @throws Exception
 */
@Transactional(isolation = Isolation.SERIALIZABLE)
public String createToken(String username, String password) throws Exception {
    Map<String, String> requestParameters = new HashMap<>();

    User userObj = userRepository.findByUsername(username);

    if (userObj != null) {
        Long userId = userObj.getId();

        requestParameters.put("username", username);
        requestParameters.put("password", password);

        // USER
        org.springframework.security.core.userdetails.User user = new org.springframework.security.core.userdetails.User(
                userId.toString(), "", new ArrayList<GrantedAuthority>());

        ClientDetails clientDetails = getAPIMgmtClient();
        TokenRequest tokenRequest = new TokenRequest(requestParameters, clientDetails.getClientId(), scopes(),
                "password");
        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
        Collection<? extends GrantedAuthority> list = authorities(userObj);
        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request,
                new UsernamePasswordAuthenticationToken(user, "", list));
        OAuth2AccessToken accessToken = tokenService.createAccessToken(oAuth2Authentication);
        return accessToken.getValue();
    }
    return null;
}

From source file:org.mitre.oauth2.service.impl.TestDefaultOAuth2ProviderTokenService.java

@Test(expected = InvalidClientException.class)
public void refreshAccessToken_clientMismatch() {

    tokenRequest = new TokenRequest(null, badClientId, null, null);

    service.refreshAccessToken(refreshTokenValue, tokenRequest);
}

From source file:org.cloudfoundry.identity.uaa.oauth.token.Saml2TokenGranter.java

@Override
public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) {
    TokenRequest adjusted = new TokenRequest(tokenRequest.getRequestParameters(), tokenRequest.getClientId(),
            tokenRequest.getScope(), tokenRequest.getGrantType());
    return super.grant(grantType, adjusted);
}

From source file:org.cloudfoundry.identity.uaa.oauth.UaaTokenServicesTests.java

@Test
public void testLoad_Opaque_AuthenticationForAUser() {
    defaultClient.setAutoApproveScopes(singleton("true"));
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResponseTypes(new HashSet(Arrays.asList(CompositeAccessToken.ID_TOKEN, "token")));
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE);
    azParameters.put(REQUEST_TOKEN_FORMAT, TokenConstants.OPAQUE);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);//  w w  w  .  j  a va 2 s. co  m
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
    assertNotNull(accessToken);
    assertTrue("Token should be composite token", accessToken instanceof CompositeAccessToken);
    CompositeAccessToken composite = (CompositeAccessToken) accessToken;
    assertThat("id_token should be JWT, thus longer than 36 characters", composite.getIdTokenValue().length(),
            greaterThan(36));
    assertThat("Opaque access token must be shorter than 37 characters", accessToken.getValue().length(),
            lessThanOrEqualTo(36));
    assertThat("Opaque refresh token must be shorter than 37 characters",
            accessToken.getRefreshToken().getValue().length(), lessThanOrEqualTo(36));

    String accessTokenValue = tokenProvisioning.retrieve(composite.getValue()).getValue();
    Map<String, Object> accessTokenClaims = tokenServices.validateToken(accessTokenValue).getClaims();
    assertEquals(true, accessTokenClaims.get(ClaimConstants.REVOCABLE));

    String refreshTokenValue = tokenProvisioning.retrieve(composite.getRefreshToken().getValue()).getValue();
    Map<String, Object> refreshTokenClaims = tokenServices.validateToken(refreshTokenValue).getClaims();
    assertEquals(true, refreshTokenClaims.get(ClaimConstants.REVOCABLE));

    OAuth2Authentication loadedAuthentication = tokenServices.loadAuthentication(accessToken.getValue());

    assertEquals(USER_AUTHORITIES, loadedAuthentication.getAuthorities());
    assertEquals(username, loadedAuthentication.getName());
    UaaPrincipal uaaPrincipal = (UaaPrincipal) defaultUserAuthentication.getPrincipal();
    assertEquals(uaaPrincipal, loadedAuthentication.getPrincipal());
    assertNull(loadedAuthentication.getDetails());

    Authentication userAuth = loadedAuthentication.getUserAuthentication();
    assertEquals(username, userAuth.getName());
    assertEquals(uaaPrincipal, userAuth.getPrincipal());
    assertTrue(userAuth.isAuthenticated());

    Map<String, String> params = new HashedMap();
    params.put("grant_type", "refresh_token");
    params.put("client_id", CLIENT_ID);
    OAuth2AccessToken newAccessToken = tokenServices.refreshAccessToken(composite.getRefreshToken().getValue(),
            new TokenRequest(params, CLIENT_ID, Collections.EMPTY_SET, "refresh_token"));
    System.out.println("newAccessToken = " + newAccessToken);
}