Example usage for org.springframework.security.oauth2.common ExpiringOAuth2RefreshToken getExpiration

List of usage examples for org.springframework.security.oauth2.common ExpiringOAuth2RefreshToken getExpiration

Introduction

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

Prototype

Date getExpiration();

Source Link

Usage

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

protected boolean isExpired(OAuth2RefreshToken refreshToken) {
    if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
        ExpiringOAuth2RefreshToken expiringToken = (ExpiringOAuth2RefreshToken) refreshToken;
        return expiringToken.getExpiration() == null
                || System.currentTimeMillis() > expiringToken.getExpiration().getTime();
    }//  w  w w .  j a v a  2s  .  co m
    return false;
}

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

/**
 * Builds or updates the data of an AuthorizationGrant object based on an access token, refresh token and
 * an authentication. If a grant is given, it will be updated. If the given authorization grant object is
 * null a new AuthorizationGrant object will be constructed and populated.
 * @param grant The grant to be updated or null if a new AuthorizationGrant is to be created.
 * @param refreshToken The refresh token
 * @param authentication The authentication
 * @return The created or updated authorization grant
 *///from   w  w w  .  ja  v  a 2  s .com
protected AuthorizationGrant buildAuthorizationGrant(AuthorizationGrant grant,
        ExpiringOAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
    log.debug("buildAuthorizationGrant");
    long now = System.currentTimeMillis();

    boolean update = true;
    if (grant == null) {
        grant = new AuthorizationGrant();
        update = false;
    }

    String clientId = authentication.getAuthorizationRequest().getClientId();
    grant.setClientId(clientId);
    grant.setAccessToken(UUID.randomUUID().toString());

    if (update) {
        grant.getGrantedPermissions().clear();
    } else {
        grant.setGrantedPermissions(new ArrayList<CertifiedClientPermission>(
                authentication.getAuthorizationRequest().getScope().size()));
    }
    long validitySeconds = accessTokenValiditySeconds;

    for (String permission : authentication.getAuthorizationRequest().getScope()) {
        CertifiedClientPermission ccPermission = ccPermissionRepository.findByPermissionName(permission,
                clientId);

        if (ccPermission == null) {
            log.warn("No permission {} found for client {}", permission, clientId);
        } else {

            grant.getGrantedPermissions().add(ccPermission);

            int permissionValiditySeconds = ccPermission.getPermission().getAccessTokenValiditySeconds();
            if (permissionValiditySeconds > 0 && validitySeconds > permissionValiditySeconds) {
                validitySeconds = permissionValiditySeconds;
            }
        }
    }

    final String name = authentication.getName();

    String legalGuardianResidentIdentificationNumber = null;
    String citizenResidentIdentificationNumber = name;
    if (name.contains("/")) {
        final String[] split = name.split("/");
        legalGuardianResidentIdentificationNumber = split[0];
        citizenResidentIdentificationNumber = split[1];
    }

    grant.setLegalGuardianResidentIdentificationNumber(legalGuardianResidentIdentificationNumber);
    grant.setResidentIdentificationNumber(citizenResidentIdentificationNumber);

    if (validitySeconds > 0) {
        final Date expirationTime = generateExpirationTime(citizenResidentIdentificationNumber,
                validitySeconds);
        grant.setAccessTokenExpires(expirationTime);
    }

    grant.setAuthenticationKey(authenticationKeyGenerator.extractKey(authentication));

    if (supportRefreshToken) {
        grant.setGrantExpires(refreshToken.getExpiration());
        grant.setRefreshToken(refreshToken.getValue());
    } else {
        grant.setGrantExpires(grant.getAccessTokenExpires());
    }
    grant.setIssueDate(new Date(now));

    log.debug("returning from buildAuthorizationGrant");
    return grant;
}

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

@Override
@Transactional(propagation = Propagation.REQUIRED)
public OAuth2AccessToken refreshAccessToken(String refreshTokenValue, AuthorizationRequest request)
        throws AuthenticationException {
    log.debug("refreshAccessToken(refreshTokenValue:{}, request:{})", refreshTokenValue, request);

    if (!supportRefreshToken) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }/*from   w w  w  . j  av a2  s . c o m*/
    AuthorizationGrant authorizationGrant = authorizationGrantRepository.findByRefreshToken(refreshTokenValue);
    if (authorizationGrant == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }

    if (!validateLegalGuardianInAuthrizationGrant(authorizationGrant)) {
        throw new InvalidGrantException(
                "Authorization grant is missing a valid legal guardian: " + refreshTokenValue);
    }

    OAuth2AccessToken accessToken = buildAccessTokenFromAuthorizationGrant(authorizationGrant, false);
    ExpiringOAuth2RefreshToken refreshToken = (ExpiringOAuth2RefreshToken) accessToken.getRefreshToken();

    if (accessToken == null || accessToken.getRefreshToken() == null) {
        throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue);
    }

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

    if (isExpired(accessToken.getRefreshToken())) {
        log.info("Removing expired authorization grant with auth key {} for client {}",
                authorizationGrant.getAuthenticationKey(), authorizationGrant.getClientId());
        authorizationGrantRepository.delete(authorizationGrant);
        throw new InvalidGrantException("Invalid refresh token: " + accessToken.getRefreshToken());
    }

    Set<String> scope = request.getScope();
    // if scope exists, we want to narrow the scope and therefore check that scope is a subset of the original scope
    // else if the scope param is empty, use the old scope from db.
    if (scope != null && scope.size() > 0) {
        if (accessToken.getScope() == null || !accessToken.getScope().containsAll(scope)) {
            throw new InvalidScopeException(
                    "Unable to narrow the scope of the client authentication to " + scope + ".",
                    accessToken.getScope());
        } else if (accessToken.getScope().size() > scope.size()) {

            // if scope is narrowed, check for already existing accesstoken
            OAuth2Authentication auth = buildAuthenticationFromAuthorizationGrant(authorizationGrant, scope);
            AuthorizationGrant grant = authorizationGrantRepository
                    .findByAuthenticationKey(authenticationKeyGenerator.extractKey(auth));

            log.info("grant: {}", grant);

            if (grant != null) {
                throw new InvalidScopeException(
                        "Unable to narrow the scope of the client authentication to " + scope
                                + ". An authorization with that scope, client and user already exists.",
                        accessToken.getScope());
            }
        }
    } else {
        scope = accessToken.getScope();
    }

    OAuth2Authentication authentication = buildAuthenticationFromAuthorizationGrant(authorizationGrant, scope);

    if (!reuseRefreshToken) {
        refreshToken = buildRefreshToken(authentication);
        authorizationGrant.setRefreshToken(refreshToken.getValue());
        authorizationGrant.setGrantExpires(refreshToken.getExpiration());
    }
    authorizationGrant = buildAuthorizationGrant(authorizationGrant, refreshToken, authentication);
    authorizationGrant = authorizationGrantRepository.save(authorizationGrant);
    OAuth2AccessToken token = buildAccessTokenFromAuthorizationGrant(authorizationGrant, false);
    log.debug("Returning from refreshAccessToken");
    return token;
}

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;
    }//  w  ww .ja va  2 s.c o m

    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

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  ww  w . j a  va 2s  .  c o  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;
}