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

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

Introduction

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

Prototype

String getValue();

Source Link

Usage

From source file:nl.surfnet.coin.api.oauth.OpenConextOauth2JdbcTokenStore.java

@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    AuthorizationRequest authorizationRequest = authentication.getAuthorizationRequest();
    String clientId = authorizationRequest.getClientId();
    ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
    if (!(clientDetails instanceof OpenConextClientDetails)) {
        throw new RuntimeException("The clientDetails is of the type '"
                + (clientDetails != null ? clientDetails.getClass() : "null")
                + "'. Required is a (sub)class of ExtendedBaseClientDetails");
    }//from   ww w  .j a  va  2 s  . c  o  m

    ClientMetaData clientMetaData = ((OpenConextClientDetails) clientDetails).getClientMetaData();

    String refreshToken = null;
    if (token.getRefreshToken() != null) {
        refreshToken = token.getRefreshToken().getValue();
    }

    String value = extractTokenKey(token.getValue());
    jdbcTemplate.update(ACCESS_TOKEN_INSERT_STATEMENT,
            new Object[] { value, new SqlLobValue(SerializationUtils.serialize(token)),
                    authenticationKeyGenerator.extractKey(authentication),
                    authentication.isClientOnly() ? null : authentication.getName(),
                    authentication.getAuthorizationRequest().getClientId(), clientMetaData.getAppEntityId(),
                    new SqlLobValue(SerializationUtils.serialize(authentication)), refreshToken },
            new int[] { Types.VARCHAR, Types.BLOB, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
                    Types.BLOB, Types.VARCHAR });

}

From source file:com.nagarro.core.oauth2.token.provider.HybrisOAuthTokenStore.java

@Override
public void storeAccessToken(final OAuth2AccessToken token, final OAuth2Authentication authentication) {
    OAuthRefreshTokenModel refreshTokenModel = null;
    if (token.getRefreshToken() != null) {
        final String refreshTokenKey = extractTokenKey(token.getRefreshToken().getValue());
        try {//from ww w .  j  ava2s .c om
            refreshTokenModel = oauthTokenService.getRefreshToken(refreshTokenKey);
        } catch (final UnknownIdentifierException e) {
            refreshTokenModel = oauthTokenService.saveRefreshToken(refreshTokenKey,
                    serializeRefreshToken(token.getRefreshToken()), serializeAuthentication(authentication));
        }
    }

    oauthTokenService.saveAccessToken(extractTokenKey(token.getValue()), serializeAccessToken(token),
            authenticationKeyGenerator.extractKey(authentication), serializeAuthentication(authentication),
            authentication.isClientOnly() ? null : authentication.getName(),
            authentication.getOAuth2Request().getClientId(), refreshTokenModel);
}

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

@Test
@DirtiesContext//from ww  w  .j  ava 2  s .  co m
public void testDoubleStoreToken() throws InterruptedException {
    OAuth2Authentication authentication = new OAuth2Authentication(
            createAuthorizationRequest(CLIENT, Collections.singleton(READ_SCOPE)),
            new TestAuthentication(false));
    OAuth2AccessToken token1 = services.createAccessToken(authentication);
    Thread.sleep(1500);
    OAuth2AccessToken token2 = services.createAccessToken(authentication);
    // Make sure we don't get the same access token twice
    Assert.assertFalse(token1.getValue().equals(token2.getValue()));
    Assert.assertFalse(token1.getExpiration().equals(token2.getExpiration()));
}

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

@Test
@DirtiesContext//from  www .j a va2 s  .  c o m
@Ignore
public void testConcurrentTokenUpdate() throws InterruptedException {
    //        ExpiringOAuth2RefreshToken expectedExpiringRefreshToken = new ExpiringOAuth2RefreshToken("testToken", new Date(
    //                System.currentTimeMillis() + 100000));
    final OAuth2Authentication authentication = new OAuth2Authentication(
            createAuthorizationRequest(CLIENT, Collections.singleton(READ_SCOPE)),
            new TestAuthentication(false));

    final OAuth2AccessToken[] accessTokens = new OAuth2AccessToken[10];
    for (int i = 0; i < 10; i++) {
        accessTokens[i] = services.createAccessToken(authentication);
    }

    int numberOfConcurrent = 1000;
    List<Thread> executors = new ArrayList<Thread>();
    for (int i = 0; i < numberOfConcurrent; i++) {
        Thread concurrentUpdater = new Thread() {

            //                private OAuth2Authentication innerAuthentication = authentication;
            //                private TransactionalAuthServerTokenServicesDelegatorImpl innerServices = services;

            @Override
            public void run() {
                System.out.println("To run createAccessToken");
                try {
                    if (Math.random() > 0.8) {
                        services.createAccessToken(authentication);
                    } else {
                        OAuth2AccessToken tk = accessTokens[(int) Math.floor(Math.random() * 10)];
                        AuthorizationRequest request = createAuthorizationRequest(CLIENT, tk.getScope());
                        services.refreshAccessToken(tk.getValue(), request);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    //                        Thread.currentThread().interrupt();
                    //                        Assert.fail("Got exception: " + e.getMessage());
                    throw new RuntimeException("failed");

                }

                System.out.println("Ran createAccessToken");
            }
        };
        executors.add(concurrentUpdater);
    }
    for (Thread executor : executors) {
        executor.start();
    }
    for (Thread executor : executors) {
        executor.join();
    }
    Assert.assertEquals(1, authorizationGrantRepository.count());
}

From source file:com.github.biegleux.gae.oauth.tokenstore.GaeTokenStore.java

@Override
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
    OAuth2AccessToken accessToken = null;

    String key = authenticationKeyGenerator.extractKey(authentication);
    try {//w  w w.ja va2  s .c o m
        GaeOAuthAccessToken gaeOAuthAccessToken = accessTokens.findByAuthenticationId(key);
        if (gaeOAuthAccessToken != null) {
            accessToken = gaeOAuthAccessToken.getToken();
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Failed to find access token for authentication " + authentication);
            }
        }
    } catch (JDOException e) {
        LOG.error("Could not extract access token for authentication " + authentication, e);
    }

    if (accessToken != null
            && !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
        removeAccessToken(accessToken.getValue());
        // Keep the store consistent (maybe the same user is represented by this authentication but the details have changed)
        storeAccessToken(accessToken, authentication);
    }
    return accessToken;
}

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

@Test
@DirtiesContext//from  www  . ja  v a  2  s  . c om
public void testRefreshedTokenHasScopes() throws Exception {
    services.setSupportRefreshToken(true);

    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(
            createAuthorizationRequest(CLIENT, Collections.singleton(READ_SCOPE)),
            new TestAuthentication(false));
    OAuth2AccessToken accessToken = services.createAccessToken(expectedAuthentication);

    AuthorizationRequest request = createAuthorizationRequest(CLIENT, Collections.<String>emptySet());
    OAuth2AccessToken refreshedAccessToken = services
            .refreshAccessToken(accessToken.getRefreshToken().getValue(), request);

    assertFalse(accessToken.getValue().equals(refreshedAccessToken.getValue()));
    assertEquals("[" + READ_SCOPE + "]", refreshedAccessToken.getScope().toString());
}

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

@Test
public void testCreateAccessTokenForAClient() {

    DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest("client",
            Arrays.asList(new String[] { "read", "write" }));
    authorizationRequest.setResourceIds(new HashSet<String>(Arrays.asList(new String[] { "scim", "clients" })));
    Map<String, String> azParameters = new HashMap<String, String>(
            authorizationRequest.getAuthorizationParameters());
    azParameters.put("grant_type", "client_credentials");
    authorizationRequest.setAuthorizationParameters(azParameters);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest, null);

    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
    Jwt tokenJwt = JwtHelper.decodeAndVerify(accessToken.getValue(), signerProvider.getVerifier());
    assertNotNull(tokenJwt);/*from w  w w.  j  a va2s. c om*/
    Map<String, Object> claims = null;
    try {
        claims = mapper.readValue(tokenJwt.getClaims(), new TypeReference<Map<String, Object>>() {
        });
    } catch (Exception e) {
        throw new IllegalStateException("Cannot read token claims", e);
    }

    assertEquals(claims.get("iss"), "http://localhost:8080/uaa/oauth/token");
    assertEquals(claims.get("client_id"), "client");
    assertNull("user_id should be null for a client token", claims.get("user_id"));
    assertEquals(claims.get("sub"), "client");
    assertNull("user_id should be null for a client token", claims.get("user_name"));
    assertEquals(claims.get("cid"), "client");
    assertEquals(claims.get("scope"), Arrays.asList(new String[] { "read", "write" }));
    assertEquals(claims.get("aud"), Arrays.asList(new String[] { "scim", "clients" }));
    assertTrue(((String) claims.get("jti")).length() > 0);
    assertTrue(((Integer) claims.get("iat")) > 0);
    assertTrue(((Integer) claims.get("exp")) > 0);
    assertTrue(((Integer) claims.get("exp")) - ((Integer) claims.get("iat")) == 60 * 60 * 12);
    assertNull(accessToken.getRefreshToken());
}

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

@Test
public void testReadAccessToken() {
    DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest("client",
            Arrays.asList(new String[] { "read", "write" }));
    authorizationRequest.setResourceIds(new HashSet<String>(Arrays.asList(new String[] { "scim", "clients" })));
    Map<String, String> azParameters = new HashMap<String, String>(
            authorizationRequest.getAuthorizationParameters());
    azParameters.put("grant_type", "authorization_code");
    authorizationRequest.setAuthorizationParameters(azParameters);
    Authentication userAuthentication = new UsernamePasswordAuthenticationToken(
            new UaaPrincipal(new UaaUser("jdsa", "password", "jdsa@vmware.com", null, null)), "n/a", null);

    Calendar expiresAt = Calendar.getInstance();
    expiresAt.add(Calendar.MILLISECOND, 3000);
    Calendar updatedAt = Calendar.getInstance();
    updatedAt.add(Calendar.MILLISECOND, -1000);

    approvalStore.addApproval(new Approval("jdsa", "client", "read", expiresAt.getTime(),
            ApprovalStatus.APPROVED, updatedAt.getTime()));
    approvalStore.addApproval(new Approval("jdsa", "client", "write", expiresAt.getTime(),
            ApprovalStatus.APPROVED, updatedAt.getTime()));

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest, userAuthentication);
    OAuth2AccessToken accessToken = testCreateAccessTokenForAUser(authentication, false);
    assertEquals(accessToken, tokenServices.readAccessToken(accessToken.getValue()));
}

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

@Test
public void testChangedExpiryForTokens() {
    BaseClientDetails clientDetails = new BaseClientDetails("client", "scim. clients", "read, write",
            "authorization_code, password, implicit, client_credentials", "update");
    clientDetails.setAccessTokenValiditySeconds(3600);
    clientDetails.setRefreshTokenValiditySeconds(36000);
    clientDetailsService.setClientDetailsStore(Collections.singletonMap("client", clientDetails));

    DefaultAuthorizationRequest authorizationRequest = new DefaultAuthorizationRequest("client",
            Arrays.asList(new String[] { "read", "write" }));
    authorizationRequest.setResourceIds(new HashSet<String>(Arrays.asList(new String[] { "scim", "clients" })));
    Map<String, String> azParameters = new HashMap<String, String>(
            authorizationRequest.getAuthorizationParameters());
    azParameters.put("grant_type", "authorization_code");
    authorizationRequest.setAuthorizationParameters(azParameters);
    Authentication userAuthentication = new UsernamePasswordAuthenticationToken(
            new UaaPrincipal(new UaaUser("jdsa", "password", "jdsa@vmware.com", null, null)), "n/a", null);

    OAuth2Authentication authentication = new OAuth2Authentication(authorizationRequest, userAuthentication);
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
    Jwt tokenJwt = JwtHelper.decodeAndVerify(accessToken.getValue(), signerProvider.getVerifier());
    assertNotNull(tokenJwt);/*  w  w  w .  j ava  2s .  c om*/
    Map<String, Object> claims = null;
    try {
        claims = mapper.readValue(tokenJwt.getClaims(), new TypeReference<Map<String, Object>>() {
        });
    } catch (Exception e) {
        throw new IllegalStateException("Cannot read token claims", e);
    }

    assertTrue(((Integer) claims.get("iat")) > 0);
    assertTrue(((Integer) claims.get("exp")) > 0);
    assertTrue(((Integer) claims.get("exp")) - ((Integer) claims.get("iat")) == 3600);
    assertNotNull(accessToken.getRefreshToken());

    Jwt refreshTokenJwt = JwtHelper.decodeAndVerify(accessToken.getRefreshToken().getValue(),
            signerProvider.getVerifier());
    assertNotNull(refreshTokenJwt);
    Map<String, Object> refreshTokenClaims = null;
    try {
        refreshTokenClaims = mapper.readValue(refreshTokenJwt.getClaims(),
                new TypeReference<Map<String, Object>>() {
                });
    } catch (Exception e) {
        throw new IllegalStateException("Cannot read token claims", e);
    }

    assertTrue(((Integer) refreshTokenClaims.get("iat")) > 0);
    assertTrue(((Integer) refreshTokenClaims.get("exp")) > 0);
    assertTrue(((Integer) refreshTokenClaims.get("exp")) - ((Integer) refreshTokenClaims.get("iat")) == 36000);
}

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

private OAuth2AccessToken testCreateAccessTokenForAUser(OAuth2Authentication authentication,
        boolean noRefreshToken) {
    OAuth2AccessToken accessToken = tokenServices.createAccessToken(authentication);
    Jwt tokenJwt = JwtHelper.decodeAndVerify(accessToken.getValue(), signerProvider.getVerifier());
    assertNotNull(tokenJwt);//  www.jav a 2 s .co m
    Map<String, Object> claims = null;
    try {
        claims = mapper.readValue(tokenJwt.getClaims(), new TypeReference<Map<String, Object>>() {
        });
    } catch (Exception e) {
        throw new IllegalStateException("Cannot read token claims", e);
    }

    assertEquals(claims.get("iss"), "http://localhost:8080/uaa/oauth/token");
    assertEquals(claims.get("client_id"), "client");
    assertNotNull(claims.get("user_id"));
    assertNotNull(claims.get("sub"));
    assertEquals(claims.get("user_name"), "jdsa");
    assertEquals(claims.get("email"), "jdsa@vmware.com");
    assertEquals(claims.get("cid"), "client");
    assertEquals(claims.get("scope"), Arrays.asList(new String[] { "read", "write" }));
    assertEquals(claims.get("aud"), Arrays.asList(new String[] { "scim", "clients" }));
    assertTrue(((String) claims.get("jti")).length() > 0);
    assertTrue(((Integer) claims.get("iat")) > 0);
    assertTrue(((Integer) claims.get("exp")) > 0);
    assertTrue(((Integer) claims.get("exp")) - ((Integer) claims.get("iat")) == 60 * 60 * 12);
    if (noRefreshToken) {
        assertNull(accessToken.getRefreshToken());
    } else {
        assertNotNull(accessToken.getRefreshToken());

        Jwt refreshTokenJwt = JwtHelper.decodeAndVerify(accessToken.getRefreshToken().getValue(),
                signerProvider.getVerifier());
        assertNotNull(refreshTokenJwt);
        Map<String, Object> refreshTokenClaims = null;
        try {
            refreshTokenClaims = mapper.readValue(refreshTokenJwt.getClaims(),
                    new TypeReference<Map<String, Object>>() {
                    });
        } catch (Exception e) {
            throw new IllegalStateException("Cannot read token claims", e);
        }

        assertEquals(refreshTokenClaims.get("iss"), "http://localhost:8080/uaa/oauth/token");
        assertNotNull(refreshTokenClaims.get("user_name"));
        assertNotNull(refreshTokenClaims.get("sub"));
        assertEquals(refreshTokenClaims.get("cid"), "client");
        assertEquals(refreshTokenClaims.get("scope"), Arrays.asList(new String[] { "read", "write" }));
        assertEquals(refreshTokenClaims.get("aud"), Arrays.asList(new String[] { "read", "write" }));
        assertTrue(((String) refreshTokenClaims.get("jti")).length() > 0);
        assertTrue(((Integer) refreshTokenClaims.get("iat")) > 0);
        assertTrue(((Integer) refreshTokenClaims.get("exp")) > 0);
        assertTrue(((Integer) refreshTokenClaims.get("exp")) - ((Integer) refreshTokenClaims.get("iat")) == 60
                * 60 * 24 * 30);
    }

    return accessToken;
}