Example usage for org.springframework.security.oauth2.common OAuth2AccessToken getRefreshToken

List of usage examples for org.springframework.security.oauth2.common OAuth2AccessToken getRefreshToken

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common OAuth2AccessToken getRefreshToken.

Prototype

OAuth2RefreshToken getRefreshToken();

Source Link

Usage

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

@Test(expected = InvalidTokenException.class)
public void testRefreshTokenAfterApprovalsMissing() {
    Calendar expiresAt = Calendar.getInstance();
    expiresAt.add(Calendar.MILLISECOND, -3000);

    approvalStore.addApproval(new Approval().setUserId(userId).setClientId(CLIENT_ID).setScope(readScope.get(0))
            .setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.DENIED));

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);/*from   w ww.  jav a 2s .c o  m*/
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    refreshAuthorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters());
    refreshAzParameters.put(GRANT_TYPE, REFRESH_TOKEN);
    refreshAuthorizationRequest.setRequestParameters(refreshAzParameters);

    tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(),
            requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"));
}

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

@Test(expected = InvalidTokenException.class)
public void testRefreshTokenAfterApprovalsMissing2() {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE);
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);/*from   ww  w .  jav  a2  s  . c  om*/
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    AuthorizationRequest refreshAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    refreshAuthorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> refreshAzParameters = new HashMap<>(refreshAuthorizationRequest.getRequestParameters());
    refreshAzParameters.put(GRANT_TYPE, REFRESH_TOKEN);
    refreshAuthorizationRequest.setRequestParameters(refreshAzParameters);

    tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(),
            requestFactory.createTokenRequest(refreshAuthorizationRequest, "refresh_token"));
}

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

@Test
public void refreshAccessTokenWithGrantTypeRestricted() {
    expectedEx.expect(InsufficientScopeException.class);
    expectedEx.expectMessage("Expected scope " + UAA_REFRESH_TOKEN + " is missing");

    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE);
    authorizationRequest.setRequestParameters(azParameters);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            defaultUserAuthentication);/*ww w.ja v  a  2  s . co  m*/
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    AuthorizationRequest reducedScopeAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, readScope);
    reducedScopeAuthorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> refreshAzParameters = new HashMap<>(
            reducedScopeAuthorizationRequest.getRequestParameters());
    refreshAzParameters.put(GRANT_TYPE, REFRESH_TOKEN);
    reducedScopeAuthorizationRequest.setRequestParameters(refreshAzParameters);

    tokenServices.setRestrictRefreshGrant(true);
    tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(),
            requestFactory.createTokenRequest(reducedScopeAuthorizationRequest, "refresh_token"));
}

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

@Test
public void refreshAccessTokenWithGrantTypeRestricted_butRefreshScopePresent() {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID,
            Arrays.asList(UAA_REFRESH_TOKEN));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE);
    authorizationRequest.setRequestParameters(azParameters);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            defaultUserAuthentication);/*from w  ww  . j a v  a 2s . c o  m*/
    tokenServices.setRestrictRefreshGrant(true);
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);

    AuthorizationRequest reducedScopeAuthorizationRequest = new AuthorizationRequest(CLIENT_ID, null);
    reducedScopeAuthorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> refreshAzParameters = new HashMap<>(
            reducedScopeAuthorizationRequest.getRequestParameters());
    refreshAzParameters.put(GRANT_TYPE, REFRESH_TOKEN);
    reducedScopeAuthorizationRequest.setRequestParameters(refreshAzParameters);

    expiresAt.add(Calendar.MILLISECOND, 300000);
    updatedAt.add(Calendar.MILLISECOND, -1000);
    approvalStore.addApproval(new Approval().setUserId(userId).setClientId(CLIENT_ID)
            .setScope(UAA_REFRESH_TOKEN).setExpiresAt(expiresAt.getTime()).setStatus(ApprovalStatus.APPROVED)
            .setLastUpdatedAt(updatedAt.getTime()));

    tokenServices.setRestrictRefreshGrant(true);
    OAuth2AccessToken refresh_token = tokenServices.refreshAccessToken(accessToken.getRefreshToken().getValue(),
            requestFactory.createTokenRequest(reducedScopeAuthorizationRequest, "refresh_token"));
    assertNotNull(refresh_token);
}

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

@Test
public void opaque_tokens_validate_signature() throws Exception {
    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 va2s  .c  o  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));

    Map<String, String> keys = new HashMap<>();
    keys.put("otherKey", "unc0uf98gv89egh4v98749978hv");
    tokenPolicy.setKeys(keys);
    tokenPolicy.setActiveKeyId("otherKey");
    IdentityZoneHolder.get().getConfig().setTokenPolicy(tokenPolicy);

    expectedEx.expect(InvalidTokenException.class);
    expectedEx.expectMessage("Invalid key ID: testKey");
    tokenServices.validateToken(accessToken.getValue());
}

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 . c  o  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);
}

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

@Test
public void testCreateAccessTokenAuthcodeGrantAdditionalAuthorizationAttributes() {
    AuthorizationRequest authorizationRequest = new AuthorizationRequest(CLIENT_ID, requestedAuthScopes);
    authorizationRequest.setResourceIds(new HashSet<>(resourceIds));
    Map<String, String> azParameters = new HashMap<>(authorizationRequest.getRequestParameters());
    azParameters.put(GRANT_TYPE, AUTHORIZATION_CODE);
    azParameters.put("authorities",
            "{\"az_attr\":{\"external_group\":\"domain\\\\group1\", \"external_id\":\"abcd1234\"}}");
    authorizationRequest.setRequestParameters(azParameters);
    Authentication userAuthentication = defaultUserAuthentication;

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest.createOAuth2Request(),
            userAuthentication);//from w  ww  .ja  va 2s .  c o  m
    OAuth2AccessToken token = tokenServices.createAccessToken(authentication);

    this.assertCommonUserAccessTokenProperties(token);
    assertThat(token, issuerUri(is(ISSUER_URI)));
    assertThat(token, scope(is(requestedAuthScopes)));
    assertThat(token, validFor(is(60 * 60 * 12)));

    OAuth2RefreshToken refreshToken = token.getRefreshToken();
    this.assertCommonUserRefreshTokenProperties(refreshToken);
    assertThat(refreshToken, OAuth2RefreshTokenMatchers.issuerUri(is(ISSUER_URI)));
    assertThat(refreshToken, OAuth2RefreshTokenMatchers.validFor(is(60 * 60 * 24 * 30)));

    this.assertCommonEventProperties(token, userId, buildJsonString(requestedAuthScopes));

    Map<String, String> azMap = new LinkedHashMap<>();
    azMap.put("external_group", "domain\\group1");
    azMap.put("external_id", "abcd1234");
    assertEquals(azMap, token.getAdditionalInformation().get("az_attr"));
}

From source file:org.infoscoop.api.oauth2.provider.ISTokenStore.java

@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    String refreshToken = null;//from w w  w.  java2 s  . c  o m
    if (token.getRefreshToken() != null) {
        refreshToken = token.getRefreshToken().getValue();
    }

    OAuth2ProviderAccessTokenDAO providerDao = OAuth2ProviderAccessTokenDAO.newInstance();
    providerDao.saveAccessToken(extractTokenKey(token.getValue()), serializeAccessToken(token),
            authenticationKeyGenerator.extractKey(authentication),
            authentication.isClientOnly() ? null : authentication.getName(),
            authentication.getAuthorizationRequest().getClientId(), serializeAuthentication(authentication),
            extractTokenKey(refreshToken));
}

From source file:org.orcid.core.oauth.service.OrcidTokenStoreServiceImpl.java

private OrcidOauth2TokenDetail populatePropertiesFromTokenAndAuthentication(OAuth2AccessToken token,
        OAuth2Authentication authentication, OrcidOauth2TokenDetail detail) {
    OAuth2Request authorizationRequest = authentication.getOAuth2Request();
    if (detail == null) {
        detail = new OrcidOauth2TokenDetail();
    }// w w  w.j av a 2s . co  m
    String clientId = authorizationRequest.getClientId();
    String authKey = KEY_GENERATOR.extractKey(authentication);
    detail.setAuthenticationKey(authKey);
    detail.setClientDetailsId(clientId);

    OAuth2RefreshToken refreshToken = token.getRefreshToken();
    if (refreshToken != null && StringUtils.isNotBlank(refreshToken.getValue())) {
        if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
            // Override the refresh token expiration from the client
            // details, and make it the same as the token itself
            detail.setRefreshTokenExpiration(token.getExpiration());
        }
        detail.setRefreshTokenValue(refreshToken.getValue());
    }
    if (!authentication.isClientOnly()) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof ProfileEntity) {
            ProfileEntity profileEntity = (ProfileEntity) authentication.getPrincipal();
            profileEntity = profileEntityCacheManager.retrieve(profileEntity.getId());
            detail.setProfile(profileEntity);
        }
    }

    detail.setTokenValue(token.getValue());
    detail.setTokenType(token.getTokenType());
    detail.setTokenExpiration(token.getExpiration());
    detail.setApproved(authorizationRequest.isApproved());
    detail.setRedirectUri(authorizationRequest.getRedirectUri());

    Set<String> resourceIds = authorizationRequest.getResourceIds();
    if (resourceIds == null || resourceIds.isEmpty()) {
        ClientDetailsEntity clientDetails = clientDetailsEntityCacheManager.retrieve(clientId);
        resourceIds = clientDetails.getResourceIds();
    }

    detail.setResourceId(OAuth2Utils.formatParameterList(resourceIds));
    detail.setResponseType(OAuth2Utils.formatParameterList(authorizationRequest.getResponseTypes()));
    detail.setScope(OAuth2Utils.formatParameterList(authorizationRequest.getScope()));

    Map<String, Object> additionalInfo = token.getAdditionalInformation();
    if (additionalInfo != null) {
        if (additionalInfo.containsKey(OrcidOauth2Constants.TOKEN_VERSION)) {
            String sVersion = String.valueOf(additionalInfo.get(OrcidOauth2Constants.TOKEN_VERSION));
            detail.setVersion(Long.valueOf(sVersion));
        } else {
            // TODO: As of Jan 2015 all tokens will be new tokens, so, we
            // will have to remove the token version code and
            // treat all tokens as new tokens
            detail.setVersion(Long.valueOf(OrcidOauth2Constants.PERSISTENT_TOKEN));
        }

        if (additionalInfo.containsKey(OrcidOauth2Constants.PERSISTENT)) {
            boolean isPersistentKey = (Boolean) additionalInfo.get(OrcidOauth2Constants.PERSISTENT);
            detail.setPersistent(isPersistentKey);
        } else {
            detail.setPersistent(false);
        }
    } else {
        detail.setPersistent(false);
    }

    return detail;
}