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

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

Introduction

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

Prototype

public DefaultExpiringOAuth2RefreshToken(String value, Date expiration) 

Source Link

Usage

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

@Override
@Transactional(propagation = Propagation.REQUIRED)
public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
    try {//from  w w w  . j  a  v  a2 s  .c om
        User user = (User) authentication.getPrincipal();
        String logsafeSSN = citizenLoggingUtil.getLogsafeSSN(user.getUsername());
        log.debug("createAccessToken authentication:{}", logsafeSSN);
    } catch (ClassCastException ignored) {
    }

    String authenticationKey = authenticationKeyGenerator.extractKey(authentication);
    log.debug("createAccessToken -> authenticationKey:{}", authenticationKey);
    AuthorizationGrant grant = authorizationGrantRepository.findByAuthenticationKey(authenticationKey);

    ExpiringOAuth2RefreshToken refreshToken = null;
    if (grant != null && isExpired(grant.getAccessTokenExpires())) { // Timestamp
        if (supportRefreshToken) {
            refreshToken = new DefaultExpiringOAuth2RefreshToken(grant.getRefreshToken(),
                    grant.getGrantExpires());
        }
    } else {
        // grant is either null, or unexpired
        refreshToken = buildRefreshToken(authentication);
    }
    grant = buildAuthorizationGrant(grant, refreshToken, authentication);
    grant = authorizationGrantRepository.save(grant);
    OAuth2AccessToken token = buildAccessTokenFromAuthorizationGrant(grant, false);
    log.debug("Returning from createAccessToken");
    return token;
}

From source file:it.smartcommunitylab.aac.oauth.NonRemovingTokenServices.java

private ExpiringOAuth2RefreshToken createRefreshToken(OAuth2Authentication authentication) {
    if (!isSupportRefreshToken(authentication.getOAuth2Request())) {
        return null;
    }//from   w w w . ja  v a  2 s .c o m
    int validitySeconds = getRefreshTokenValiditySeconds(authentication.getOAuth2Request());
    ExpiringOAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken(
            UUID.randomUUID().toString(), new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
    return refreshToken;
}

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

@Test
public void testRemoveRefreshToken() {
    OAuth2RefreshToken expectedExpiringRefreshToken = new DefaultExpiringOAuth2RefreshToken("testToken",
            new Date());
    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(
            RequestTokenFactory.createOAuth2Request("id", false), new TestAuthentication("test2", false));
    getTokenStore().storeRefreshToken(expectedExpiringRefreshToken, expectedAuthentication);
    getTokenStore().removeRefreshToken(expectedExpiringRefreshToken);

    assertNull(getTokenStore().readRefreshToken("testToken"));
}

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

protected ExpiringOAuth2RefreshToken buildRefreshToken(OAuth2Authentication authentication) {
    log.debug("buildRefreshToken");
    if (!supportRefreshToken) {
        return null;
    }/*from   www. j  a v  a2s  .co m*/
    long validitySeconds = getRefreshTokenValiditySeconds(authentication.getAuthorizationRequest());
    ExpiringOAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken(
            UUID.randomUUID().toString(), new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));
    log.debug("returning from buildRefreshToken");
    return refreshToken;
}

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.
 *//* ww  w .j a  va2 s .c om*/
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.token.UaaTokenServices.java

private ExpiringOAuth2RefreshToken createRefreshToken(OAuth2Authentication authentication) {

    String grantType = authentication.getOAuth2Request().getRequestParameters().get("grant_type");
    if (!isRefreshTokenSupported(grantType)) {
        return null;
    }//from w ww  .  j ava  2s  .c om

    Map<String, String> additionalAuthorizationAttributes = getAdditionalAuthorizationAttributes(
            authentication.getOAuth2Request().getRequestParameters().get("authorities"));

    int validitySeconds = getRefreshTokenValiditySeconds(authentication.getOAuth2Request());
    ExpiringOAuth2RefreshToken token = new DefaultExpiringOAuth2RefreshToken(UUID.randomUUID().toString(),
            new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));

    String userId = getUserId(authentication);
    UaaUser user = userDatabase.retrieveUserById(userId);

    String content;
    try {
        content = mapper.writeValueAsString(
                createJWTRefreshToken(token, user, authentication.getOAuth2Request().getScope(),
                        authentication.getOAuth2Request().getClientId(), grantType,
                        additionalAuthorizationAttributes, authentication.getOAuth2Request().getResourceIds()));
    } catch (Exception e) {
        throw new IllegalStateException("Cannot convert access token to JSON", e);
    }
    String jwtToken = JwtHelper.encode(content, signerProvider.getSigner()).getEncoded();

    ExpiringOAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken(jwtToken,
            token.getExpiration());

    return refreshToken;
}

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

@Override
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, TokenRequest request)
        throws AuthenticationException {
    if (null == refreshTokenValue) {
        throw new InvalidTokenException("Invalid refresh token (empty token)");
    }/*from  w  w w.jav  a  2s .  c om*/

    if (!"refresh_token".equals(request.getRequestParameters().get("grant_type"))) {
        throw new InvalidGrantException(
                "Invalid grant type: " + request.getRequestParameters().get("grant_type"));
    }

    TokenValidation tokenValidation = validateToken(refreshTokenValue);
    Map<String, Object> claims = tokenValidation.getClaims();
    refreshTokenValue = tokenValidation.getJwt().getEncoded();

    @SuppressWarnings("unchecked")
    ArrayList<String> tokenScopes = (ArrayList<String>) claims.get(SCOPE);
    if (isRestrictRefreshGrant() && !tokenScopes.contains(UAA_REFRESH_TOKEN)) {
        throw new InsufficientScopeException(String.format("Expected scope %s is missing", UAA_REFRESH_TOKEN));
    }

    // TODO: Should reuse the access token you get after the first
    // successful authentication.
    // You will get an invalid_grant error if your previous token has not
    // expired yet.
    // OAuth2RefreshToken refreshToken =
    // tokenStore.readRefreshToken(refreshTokenValue);
    // if (refreshToken == null) {
    // throw new InvalidGrantException("Invalid refresh token: " +
    // refreshTokenValue);
    // }

    String clientId = (String) claims.get(CID);
    if (clientId == null || !clientId.equals(request.getClientId())) {
        throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue);
    }

    String userid = (String) claims.get(USER_ID);

    String refreshTokenId = (String) claims.get(JTI);
    String accessTokenId = generateUniqueTokenId();

    boolean opaque = TokenConstants.OPAQUE
            .equals(request.getRequestParameters().get(TokenConstants.REQUEST_TOKEN_FORMAT));
    boolean revocable = opaque || (claims.get(REVOCABLE) == null ? false : (Boolean) claims.get(REVOCABLE));

    // TODO: Need to add a lookup by id so that the refresh token does not
    // need to contain a name
    UaaUser user = userDatabase.retrieveUserById(userid);
    ClientDetails client = clientDetailsService.loadClientByClientId(clientId);

    Integer refreshTokenIssuedAt = (Integer) claims.get(IAT);
    long refreshTokenIssueDate = refreshTokenIssuedAt.longValue() * 1000l;

    Integer refreshTokenExpiry = (Integer) claims.get(EXP);
    long refreshTokenExpireDate = refreshTokenExpiry.longValue() * 1000l;

    if (new Date(refreshTokenExpireDate).before(new Date())) {
        throw new InvalidTokenException("Invalid refresh token (expired): " + refreshTokenValue + " expired at "
                + new Date(refreshTokenExpireDate));
    }

    // default request scopes to what is in the refresh token
    Set<String> requestedScopes = request.getScope();
    if (requestedScopes.isEmpty()) {
        requestedScopes = new HashSet<>(tokenScopes);
    }

    // The user may not request scopes that were not part of the refresh
    // token
    if (tokenScopes.isEmpty() || !tokenScopes.containsAll(requestedScopes)) {
        throw new InvalidScopeException(
                "Unable to narrow the scope of the client authentication to " + requestedScopes + ".",
                new HashSet<>(tokenScopes));
    }

    // from this point on, we only care about the scopes requested, not what
    // is in the refresh token
    // ensure all requested scopes are approved: either automatically or
    // explicitly by the user
    String grantType = claims.get(GRANT_TYPE).toString();
    checkForApproval(userid, clientId, requestedScopes, getAutoApprovedScopes(grantType, tokenScopes, client));

    // if we have reached so far, issue an access token
    Integer validity = client.getAccessTokenValiditySeconds();

    String nonce = (String) claims.get(NONCE);

    @SuppressWarnings("unchecked")
    Map<String, String> additionalAuthorizationInfo = (Map<String, String>) claims.get(ADDITIONAL_AZ_ATTR);

    @SuppressWarnings("unchecked")
    Map<String, String> externalAttributes = (Map<String, String>) claims.get(EXTERNAL_ATTR);

    String revocableHashSignature = (String) claims.get(REVOCATION_SIGNATURE);
    if (hasText(revocableHashSignature)) {
        String clientSecretForHash = client.getClientSecret();
        if (clientSecretForHash != null && clientSecretForHash.split(" ").length > 1) {
            clientSecretForHash = clientSecretForHash.split(" ")[1];
        }
        String newRevocableHashSignature = UaaTokenUtils.getRevocableTokenSignature(client, clientSecretForHash,
                user);
        if (!revocableHashSignature.equals(newRevocableHashSignature)) {
            throw new TokenRevokedException(refreshTokenValue);
        }
    }

    Set<String> audience = new HashSet<>((ArrayList<String>) claims.get(AUD));

    int zoneAccessTokenValidity = getZoneAccessTokenValidity();

    CompositeAccessToken accessToken = createAccessToken(accessTokenId, user.getId(), user,
            (claims.get(AUTH_TIME) != null) ? new Date(((Long) claims.get(AUTH_TIME)) * 1000l) : null,
            validity != null ? validity.intValue() : zoneAccessTokenValidity, null, requestedScopes, clientId,
            audience /*request.createOAuth2Request(client).getResourceIds()*/, grantType, refreshTokenValue,
            nonce, additionalAuthorizationInfo, externalAttributes, new HashSet<>(), revocableHashSignature,
            false, null, //TODO populate response types
            null, revocable, null, null);

    DefaultExpiringOAuth2RefreshToken expiringRefreshToken = new DefaultExpiringOAuth2RefreshToken(
            refreshTokenValue, new Date(refreshTokenExpireDate));
    return persistRevocableToken(accessTokenId, refreshTokenId, accessToken, expiringRefreshToken, clientId,
            user.getId(), opaque, revocable);

}

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

private ExpiringOAuth2RefreshToken createRefreshToken(String tokenId, OAuth2Authentication authentication,
        String revocableHashSignature, boolean revocable) {

    String grantType = authentication.getOAuth2Request().getRequestParameters().get("grant_type");
    Set<String> scope = authentication.getOAuth2Request().getScope();
    if (!isRefreshTokenSupported(grantType, scope)) {
        return null;
    }//from  w w w. j  av  a2s .co m

    Map<String, String> additionalAuthorizationAttributes = getAdditionalAuthorizationAttributes(
            authentication.getOAuth2Request().getRequestParameters().get("authorities"));

    int validitySeconds = getRefreshTokenValiditySeconds(authentication.getOAuth2Request());
    ExpiringOAuth2RefreshToken token = new DefaultExpiringOAuth2RefreshToken(tokenId,
            new Date(System.currentTimeMillis() + (validitySeconds * 1000L)));

    String userId = getUserId(authentication);

    UaaUser user = userDatabase.retrieveUserById(userId);

    Map<String, String> externalAttributes = null;
    if (uaaTokenEnhancer != null) {
        externalAttributes = uaaTokenEnhancer.getExternalAttributes(authentication);
    }

    String content;
    try {
        content = JsonUtils.writeValueAsString(
                createJWTRefreshToken(token, tokenId, user, authentication.getOAuth2Request().getScope(),
                        authentication.getOAuth2Request().getClientId(), grantType,
                        additionalAuthorizationAttributes, authentication.getOAuth2Request().getResourceIds(),
                        revocableHashSignature, revocable, externalAttributes));
    } catch (JsonUtils.JsonUtilException e) {
        throw new IllegalStateException("Cannot convert access token to JSON", e);
    }
    String jwtToken = JwtHelper.encode(content, KeyInfo.getActiveKey().getSigner()).getEncoded();

    ExpiringOAuth2RefreshToken refreshToken = new DefaultExpiringOAuth2RefreshToken(jwtToken,
            token.getExpiration());

    return refreshToken;
}