Search in sources :

Example 41 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project ORCID-Source by ORCID.

the class OrcidTokenStoreServiceImpl method getOauth2AccessTokenFromDetails.

private OAuth2AccessToken getOauth2AccessTokenFromDetails(OrcidOauth2TokenDetail detail) {
    DefaultOAuth2AccessToken token = null;
    if (detail != null && StringUtils.isNotBlank(detail.getTokenValue())) {
        token = new DefaultOAuth2AccessToken(detail.getTokenValue());
        token.setExpiration(detail.getTokenExpiration());
        token.setScope(OAuth2Utils.parseParameterList(detail.getScope()));
        token.setTokenType(detail.getTokenType());
        String refreshToken = detail.getRefreshTokenValue();
        OAuth2RefreshToken rt;
        if (StringUtils.isNotBlank(refreshToken)) {
            if (detail.getRefreshTokenExpiration() != null) {
                rt = new DefaultExpiringOAuth2RefreshToken(detail.getRefreshTokenValue(), detail.getRefreshTokenExpiration());
            } else {
                rt = new DefaultOAuth2RefreshToken(detail.getRefreshTokenValue());
            }
            token.setRefreshToken(rt);
        }
        ProfileEntity profile = detail.getProfile();
        if (profile != null) {
            Map<String, Object> additionalInfo = new HashMap<String, Object>();
            additionalInfo.put(OrcidOauth2Constants.ORCID, profile.getId());
            additionalInfo.put(OrcidOauth2Constants.PERSISTENT, detail.isPersistent());
            additionalInfo.put(OrcidOauth2Constants.DATE_CREATED, detail.getDateCreated());
            additionalInfo.put(OrcidOauth2Constants.TOKEN_VERSION, detail.getVersion());
            token.setAdditionalInformation(additionalInfo);
        }
        String clientId = detail.getClientDetailsId();
        if (!PojoUtil.isEmpty(clientId)) {
            Map<String, Object> additionalInfo = new HashMap<String, Object>();
            Map<String, Object> additionalInfoInToken = token.getAdditionalInformation();
            if (additionalInfoInToken != null && !additionalInfoInToken.isEmpty()) {
                additionalInfo.putAll(additionalInfoInToken);
            }
            // Copy to a new one to avoid unmodifiable
            additionalInfo.put(OrcidOauth2Constants.CLIENT_ID, clientId);
            token.setAdditionalInformation(additionalInfo);
        }
    }
    return token;
}
Also used : ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) HashMap(java.util.HashMap) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity)

Example 42 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project ORCID-Source by ORCID.

the class OrcidTokenStoreServiceImpl method populatePropertiesFromTokenAndAuthentication.

private OrcidOauth2TokenDetail populatePropertiesFromTokenAndAuthentication(OAuth2AccessToken token, OAuth2Authentication authentication, OrcidOauth2TokenDetail detail) {
    OAuth2Request authorizationRequest = authentication.getOAuth2Request();
    if (detail == null) {
        detail = new OrcidOauth2TokenDetail();
    }
    // Update to put auth code in token detail so it can be revoked based on code if needed.
    if (authentication.getOAuth2Request().getRequestParameters().get("code") != null) {
        detail.setAuthorizationCode(authentication.getOAuth2Request().getRequestParameters().get("code").toString());
    }
    String clientId = authorizationRequest.getClientId();
    String authKey = authenticationKeyGenerator.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;
}
Also used : ClientDetailsEntity(org.orcid.persistence.jpa.entities.ClientDetailsEntity) OAuth2Request(org.springframework.security.oauth2.provider.OAuth2Request) ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) OrcidOauth2TokenDetail(org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail) ProfileEntity(org.orcid.persistence.jpa.entities.ProfileEntity) ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)

Example 43 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security-oauth by spring-projects.

the class RedisTokenStore method storeAccessToken.

@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
    byte[] serializedAccessToken = serialize(token);
    byte[] serializedAuth = serialize(authentication);
    byte[] accessKey = serializeKey(ACCESS + token.getValue());
    byte[] authKey = serializeKey(AUTH + token.getValue());
    byte[] authToAccessKey = serializeKey(AUTH_TO_ACCESS + authenticationKeyGenerator.extractKey(authentication));
    byte[] approvalKey = serializeKey(UNAME_TO_ACCESS + getApprovalKey(authentication));
    byte[] clientId = serializeKey(CLIENT_ID_TO_ACCESS + authentication.getOAuth2Request().getClientId());
    RedisConnection conn = getConnection();
    try {
        conn.openPipeline();
        if (springDataRedis_2_0) {
            try {
                this.redisConnectionSet_2_0.invoke(conn, accessKey, serializedAccessToken);
                this.redisConnectionSet_2_0.invoke(conn, authKey, serializedAuth);
                this.redisConnectionSet_2_0.invoke(conn, authToAccessKey, serializedAccessToken);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        } else {
            conn.set(accessKey, serializedAccessToken);
            conn.set(authKey, serializedAuth);
            conn.set(authToAccessKey, serializedAccessToken);
        }
        if (!authentication.isClientOnly()) {
            conn.rPush(approvalKey, serializedAccessToken);
        }
        conn.rPush(clientId, serializedAccessToken);
        if (token.getExpiration() != null) {
            int seconds = token.getExpiresIn();
            conn.expire(accessKey, seconds);
            conn.expire(authKey, seconds);
            conn.expire(authToAccessKey, seconds);
            conn.expire(clientId, seconds);
            conn.expire(approvalKey, seconds);
        }
        OAuth2RefreshToken refreshToken = token.getRefreshToken();
        if (refreshToken != null && refreshToken.getValue() != null) {
            byte[] refresh = serialize(token.getRefreshToken().getValue());
            byte[] auth = serialize(token.getValue());
            byte[] refreshToAccessKey = serializeKey(REFRESH_TO_ACCESS + token.getRefreshToken().getValue());
            byte[] accessToRefreshKey = serializeKey(ACCESS_TO_REFRESH + token.getValue());
            if (springDataRedis_2_0) {
                try {
                    this.redisConnectionSet_2_0.invoke(conn, refreshToAccessKey, auth);
                    this.redisConnectionSet_2_0.invoke(conn, accessToRefreshKey, refresh);
                } catch (Exception ex) {
                    throw new RuntimeException(ex);
                }
            } else {
                conn.set(refreshToAccessKey, auth);
                conn.set(accessToRefreshKey, refresh);
            }
            if (refreshToken instanceof ExpiringOAuth2RefreshToken) {
                ExpiringOAuth2RefreshToken expiringRefreshToken = (ExpiringOAuth2RefreshToken) refreshToken;
                Date expiration = expiringRefreshToken.getExpiration();
                if (expiration != null) {
                    int seconds = Long.valueOf((expiration.getTime() - System.currentTimeMillis()) / 1000L).intValue();
                    conn.expire(refreshToAccessKey, seconds);
                    conn.expire(accessToRefreshKey, seconds);
                }
            }
        }
        conn.closePipeline();
    } finally {
        conn.close();
    }
}
Also used : ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) Date(java.util.Date) RedisConnection(org.springframework.data.redis.connection.RedisConnection) ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)

Example 44 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security-oauth by spring-projects.

the class TokenStoreBaseTests method testStoreRefreshToken.

@Test
public /**
 * NB: This used to test expiring refresh tokens. That test has been moved to sub-classes since not all stores support the functionality
 */
void testStoreRefreshToken() {
    String refreshToken = "testToken" + UUID.randomUUID();
    DefaultOAuth2RefreshToken expectedRefreshToken = new DefaultOAuth2RefreshToken(refreshToken);
    OAuth2Authentication expectedAuthentication = new OAuth2Authentication(RequestTokenFactory.createOAuth2Request("id", false), new TestAuthentication("test2", false));
    getTokenStore().storeRefreshToken(expectedRefreshToken, expectedAuthentication);
    OAuth2RefreshToken actualExpiringRefreshToken = getTokenStore().readRefreshToken(refreshToken);
    assertEquals(expectedRefreshToken, actualExpiringRefreshToken);
    assertEquals(expectedAuthentication, getTokenStore().readAuthenticationForRefreshToken(expectedRefreshToken));
    getTokenStore().removeRefreshToken(expectedRefreshToken);
    assertNull(getTokenStore().readRefreshToken(refreshToken));
    assertNull(getTokenStore().readAuthentication(expectedRefreshToken.getValue()));
}
Also used : DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) Test(org.junit.Test)

Example 45 with OAuth2RefreshToken

use of org.springframework.security.oauth2.core.OAuth2RefreshToken in project spring-security by spring-projects.

the class TestOAuth2AuthorizationCodeAuthenticationTokens method authenticated.

public static OAuth2AuthorizationCodeAuthenticationToken authenticated() {
    ClientRegistration registration = TestClientRegistrations.clientRegistration().build();
    OAuth2AuthorizationExchange exchange = TestOAuth2AuthorizationExchanges.success();
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
    OAuth2RefreshToken refreshToken = TestOAuth2RefreshTokens.refreshToken();
    return new OAuth2AuthorizationCodeAuthenticationToken(registration, exchange, accessToken, refreshToken);
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)

Aggregations

OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)32 Test (org.junit.jupiter.api.Test)29 OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)26 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)22 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)22 ClientRequest (org.springframework.web.reactive.function.client.ClientRequest)18 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)17 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)16 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)14 Test (org.junit.Test)13 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)12 Instant (java.time.Instant)11 Date (java.util.Date)11 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)11 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)10 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)9 HashMap (java.util.HashMap)8 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)8 HttpHeaders (org.springframework.http.HttpHeaders)5 LinkedHashMap (java.util.LinkedHashMap)4