Example usage for org.springframework.security.oauth2.common DefaultOAuth2AccessToken DefaultOAuth2AccessToken

List of usage examples for org.springframework.security.oauth2.common DefaultOAuth2AccessToken DefaultOAuth2AccessToken

Introduction

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

Prototype

public DefaultOAuth2AccessToken(OAuth2AccessToken accessToken) 

Source Link

Document

Copy constructor for access token.

Usage

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

@Test
public void testRevokeTokenForClient() throws Exception {
    Mockito.when(tokenServices.findTokensByClientId("foo"))
            .thenReturn(Collections.<OAuth2AccessToken>singleton(new DefaultOAuth2AccessToken("FOO")));
    Mockito.when(tokenServices.revokeToken("FOO")).thenReturn(true);
    SimpleMessage result = endpoints.revokeClientToken("foo", new StandardPasswordEncoder().encode("FOO"),
            new TestingAuthenticationToken("foo", ""));
    assertEquals("ok", result.getStatus());
}

From source file:com.ge.predix.uaa.token.lib.TestTokenUtil.java

private DefaultOAuth2AccessToken createAccessToken(final String issuerId, final String userId,
        final String username, final String userEmail, final int validitySeconds,
        final Collection<GrantedAuthority> clientScopes, final Set<String> requestedScopes,
        final String clientId, final Set<String> resourceIds, final String grantType, final String refreshToken,
        final Map<String, String> additionalAuthorizationAttributes, final Set<String> responseTypes,
        final String revocableHashSignature, final long issuedAtMillis, final String zoneId) {

    String tokenId = UUID.randomUUID().toString();
    DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(tokenId);
    if (validitySeconds > 0) {
        accessToken.setExpiration(new Date(issuedAtMillis + (validitySeconds * 1000L)));
    }//from  w  ww .j  a v a  2  s.  com
    accessToken.setRefreshToken(refreshToken == null ? null : new DefaultOAuth2RefreshToken(refreshToken));

    if (null == requestedScopes || requestedScopes.size() == 0) {
        // logger.debug("No scopes were granted");
        throw new InvalidTokenException("No scopes were granted");
    }

    accessToken.setScope(requestedScopes);

    Map<String, Object> info = new HashMap<String, Object>();
    info.put(JTI, accessToken.getValue());
    if (null != additionalAuthorizationAttributes) {
        info.put(ADDITIONAL_AZ_ATTR, additionalAuthorizationAttributes);
    }
    accessToken.setAdditionalInformation(info);

    String content;
    try {
        content = JsonUtils.writeValueAsString(createJWTAccessToken(accessToken, issuerId, userId, username,
                userEmail, clientScopes, requestedScopes, clientId, resourceIds, grantType, refreshToken,
                revocableHashSignature, issuedAtMillis, zoneId));
    } catch (JsonUtils.JsonUtilException e) {
        throw new IllegalStateException("Cannot convert access token to JSON", e);
    }
    String token = JwtHelper.encode(content, this.signer).getEncoded();

    // This setter copies the value and returns. Don't change.
    accessToken.setValue(token);

    return accessToken;

}

From source file:com.cedac.security.oauth2.provider.token.store.TokenStoreBaseTests.java

@Test
public void testGetAccessTokenForDeletedUser() throws Exception {
    //Test approved request
    OAuth2Request storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", true);
    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(storedOAuth2Request,
            new TestAuthentication("test", true));
    OAuth2AccessToken expectedOAuth2AccessToken = new DefaultOAuth2AccessToken("testToken");
    getTokenStore().storeAccessToken(expectedOAuth2AccessToken, expectedAuthentication);
    assertEquals(expectedOAuth2AccessToken, getTokenStore().getAccessToken(expectedAuthentication));
    assertEquals(expectedAuthentication,
            getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()));

    //Test unapproved request
    storedOAuth2Request = RequestTokenFactory.createOAuth2Request("id", false);
    OAuth2Authentication anotherAuthentication = new OAuth2Authentication(storedOAuth2Request,
            new TestAuthentication("test", true));
    assertEquals(expectedOAuth2AccessToken, getTokenStore().getAccessToken(anotherAuthentication));
    // The generated key for the authentication is the same as before, but the two auths are not equal. This could
    // happen if there are 2 users in a system with the same username, or (more likely), if a user account was
    // deleted and re-created.
    assertEquals(anotherAuthentication.getUserAuthentication(),
            getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()).getUserAuthentication());
    // The authorizationRequest does not match because it is unapproved, but the token was granted to an approved request
    assertFalse(storedOAuth2Request.equals(
            getTokenStore().readAuthentication(expectedOAuth2AccessToken.getValue()).getOAuth2Request()));
}

From source file:org.apigw.authserver.web.controller.CertifiedClientsControllerTest.java

private void commonMocks() {
    //Collection of Oauthtokens to return when asked for in the controller
    Collection<OAuth2AccessToken> tokens = new ArrayList<OAuth2AccessToken>();
    DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken("MOCK_TOKEN_VALUE");
    //Add some scopes
    Set<String> scope = new HashSet<String>();
    scope.add("MOCK_SCOPE_ITEM_1");
    scope.add("MOCK_SCOPE_ITEM_2");

    //Placeholder for additionalInformation
    Map<String, Object> addInfo = new HashMap<String, Object>();
    addInfo.put("authorization_grant_id", "MOCK_GRANT_ID");

    //Set all relevant things on this accessToken
    accessToken.setScope(scope);/* w ww  .j  a va 2  s. c  om*/
    accessToken.setExpiration(new DateTime().plusDays(1).toDate());
    accessToken.setAdditionalInformation(addInfo);

    tokens.add(accessToken);

    //Mock encryptedConsumerTokenService interactions
    Mockito.when(encryptedConsumerTokenService.findTokensByUserName(anyString())).thenReturn(tokens);
    Mockito.when(encryptedConsumerTokenService.getClientId("MOCK_TOKEN_VALUE"))
            .thenReturn("INSTALLED_CLIENT_ID");

    //CertifiedClients to return from clientDetailsServices mock
    List<CertifiedClient> clients = new ArrayList<CertifiedClient>();
    CertifiedClient installedClient = new CertifiedClient();
    CertifiedClient availableClient = new CertifiedClient();
    installedClient.setName("INSTALLED_CLIENT_NAME");
    installedClient.setClientId("INSTALLED_CLIENT_ID");
    installedClient.setOrganization("INSTALLED_CLIENT_ORGANIZATION");
    installedClient.setDescription("A description");

    availableClient.setName("AVAILABLE_CLIENT_NAME");
    availableClient.setClientId("AVAILABLE_CLIENT_ID");
    availableClient.setOrganization("AVAILABLE_CLIENT_ORGANIZATION");
    availableClient.setDescription("A description");
    availableClient.setClientUrl("http://somewhere");

    clients.add(installedClient);
    clients.add(availableClient);

    //Mock clientDetailsService interactions
    Mockito.when(clientDetailsService.findAllClients()).thenReturn(clients);
    Mockito.when(clientDetailsService.loadClientByClientId("INSTALLED_CLIENT_ID")).thenReturn(installedClient);

    //Permission to return from permissionServices mock
    Permission mockPermission = new Permission();
    mockPermission.setDescription("MOCK_ROLE_DESCRIPTION");

    //Mock scopeservices
    Mockito.when(permissionServices.getPermissionByName(anyString())).thenReturn(mockPermission);
}

From source file:com.cedac.security.oauth2.provider.token.store.TokenStoreBaseTests.java

@Test
public void testRemovedTokenCannotBeFoundByUsername() {
    OAuth2AccessToken token = new DefaultOAuth2AccessToken("testToken");
    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(
            RequestTokenFactory.createOAuth2Request("id", false), new TestAuthentication("test2", false));
    getTokenStore().storeAccessToken(token, expectedAuthentication);
    getTokenStore().removeAccessToken(token);
    Collection<OAuth2AccessToken> tokens = getTokenStore().findTokensByClientIdAndUserName("id", "test2");
    assertFalse(tokens.contains(token));
    assertTrue(tokens.isEmpty());//from   w ww . j a va 2s .  c o  m
}

From source file:org.apigw.authserver.svc.impl.TokenServicesImpl.java

/**
 * Returns a new access token, shallow-copied from the access token contained in the authorization grant.
 * @param grant The authorization grant holding the access token.
 * @param includeAuthorizationGrantId True if the additional information needs to include authorization_grant_id
 * @return An OAuth2AccessToken populated with information from the given authorization grant.
 */// w ww  .  ja v a  2 s  . c  o  m
protected OAuth2AccessToken buildAccessTokenFromAuthorizationGrant(AuthorizationGrant grant,
        boolean includeAuthorizationGrantId) {
    log.debug("buildAccessTokenFromAuthorizationGrant");
    DefaultOAuth2AccessToken accessToken = new DefaultOAuth2AccessToken(grant.getAccessToken());

    // access token and grant have the same expiry date
    accessToken.setExpiration(grant.getAccessTokenExpires());

    if (supportRefreshToken) {
        accessToken.setRefreshToken(
                new DefaultExpiringOAuth2RefreshToken(grant.getRefreshToken(), grant.getGrantExpires()));
    }
    accessToken.setScope(buildScopeFromAuthorizationGrant(grant));
    accessToken.setTokenType(OAuth2AccessToken.BEARER_TYPE);
    Map<String, Object> additionalInformation = new HashMap<String, Object>();
    additionalInformation.put("issue_date", grant.getIssueDate());
    if (includeAuthorizationGrantId) {
        additionalInformation.put("authorization_grant_id", grant.getId());
    }

    accessToken.setAdditionalInformation(additionalInformation);
    log.debug("Returning from buildAccessTokenFromAuthorizationGrant");
    return accessToken;
}

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

public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    DefaultOAuth2AccessToken result = new DefaultOAuth2AccessToken(accessToken);
    String tokenId = result.getValue();
    result.setAdditionalInformation(Collections.<String, Object>singletonMap("token_id", tokenId));
    return result.setValue(createAccessTokenValue(accessToken, authentication));
}

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

@Test
public void test_using_opaque_parameter_on_refresh_grant() {
    OAuth2AccessToken accessToken = performPasswordGrant(TokenConstants.TokenFormat.OPAQUE.getStringValue());
    OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
    String refreshTokenValue = refreshToken.getValue();

    Map<String, String> parameters = new HashMap<>();
    parameters.put(REQUEST_TOKEN_FORMAT, OPAQUE);
    TokenRequest refreshTokenRequest = getRefreshTokenRequest(parameters);

    //validate both opaque and JWT refresh tokens
    for (String s : Arrays.asList(refreshTokenValue, tokens.get(refreshTokenValue).getValue())) {
        OAuth2AccessToken refreshedAccessToken = tokenServices.refreshAccessToken(s, refreshTokenRequest);
        assertThat("Token value should be equal to or lesser than 36 characters",
                refreshedAccessToken.getValue().length(), lessThanOrEqualTo(36));
        assertCommonUserAccessTokenProperties(
                new DefaultOAuth2AccessToken(tokens.get(refreshedAccessToken).getValue()));
    }/*from  w  w w  .jav a  2s  .  c o  m*/
}

From source file:org.opentestsystem.shared.security.oauth.resource.SbacTokenConverter.java

@Override
@SuppressWarnings("unchecked")
public OAuth2AccessToken extractAccessToken(final String value, final Map<String, ?> map) {
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(value);
    Map<String, Object> info = new HashMap<String, Object>(map);
    info.remove(EXPIRES);/*from w w w.  j  a v  a2s. com*/
    info.remove(AUD);
    info.remove(CLIENT_ID);
    info.remove(SCOPE);
    if (map.containsKey(EXPIRES)) {
        long expires = new Date().getTime() + ((Integer) map.get(EXPIRES) * 1000L);
        token.setExpiration(new Date(expires));
    }
    final Collection<String> scope = (Collection<String>) map.get(SCOPE);
    if (scope != null) {
        token.setScope(Sets.newHashSet(scope));
    }
    token.setAdditionalInformation(info);
    return token;
}