Search in sources :

Example 36 with OAuth2AccessToken

use of org.springframework.security.oauth2.common.OAuth2AccessToken in project spring-security-oauth by spring-projects.

the class AbstractDefaultTokenServicesTests method testRefreshTokenRequestHasRefreshFlag.

@Test
public void testRefreshTokenRequestHasRefreshFlag() throws Exception {
    ExpiringOAuth2RefreshToken expectedExpiringRefreshToken = (ExpiringOAuth2RefreshToken) getTokenServices().createAccessToken(createAuthentication()).getRefreshToken();
    TokenRequest tokenRequest = new TokenRequest(Collections.singletonMap("client_id", "id"), "id", Collections.singleton("read"), null);
    final AtomicBoolean called = new AtomicBoolean(false);
    getTokenServices().setTokenEnhancer(new TokenEnhancer() {

        @Override
        public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
            assertTrue(authentication.getOAuth2Request().isRefresh());
            called.set(true);
            return accessToken;
        }
    });
    getTokenServices().refreshAccessToken(expectedExpiringRefreshToken.getValue(), tokenRequest);
    assertTrue(called.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) TokenRequest(org.springframework.security.oauth2.provider.TokenRequest) ExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) Test(org.junit.Test)

Example 37 with OAuth2AccessToken

use of org.springframework.security.oauth2.common.OAuth2AccessToken in project spring-security-oauth by spring-projects.

the class AbstractAuthorizationCodeProviderTests method setupAccessTokenProvider.

@BeforeOAuth2Context
public void setupAccessTokenProvider() {
    accessTokenProvider = new AuthorizationCodeAccessTokenProvider() {

        private ResponseExtractor<OAuth2AccessToken> extractor = super.getResponseExtractor();

        private ResponseExtractor<ResponseEntity<Void>> authExtractor = super.getAuthorizationResponseExtractor();

        private ResponseErrorHandler errorHandler = super.getResponseErrorHandler();

        @Override
        protected ResponseErrorHandler getResponseErrorHandler() {
            return new DefaultResponseErrorHandler() {

                public void handleError(ClientHttpResponse response) throws IOException {
                    response.getHeaders();
                    response.getStatusCode();
                    tokenEndpointResponse = response;
                    errorHandler.handleError(response);
                }
            };
        }

        @Override
        protected ResponseExtractor<OAuth2AccessToken> getResponseExtractor() {
            return new ResponseExtractor<OAuth2AccessToken>() {

                public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException {
                    try {
                        response.getHeaders();
                        response.getStatusCode();
                        tokenEndpointResponse = response;
                        return extractor.extractData(response);
                    } catch (ResourceAccessException e) {
                        return null;
                    }
                }
            };
        }

        @Override
        protected ResponseExtractor<ResponseEntity<Void>> getAuthorizationResponseExtractor() {
            return new ResponseExtractor<ResponseEntity<Void>>() {

                public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
                    response.getHeaders();
                    response.getStatusCode();
                    tokenEndpointResponse = response;
                    return authExtractor.extractData(response);
                }
            };
        }
    };
    context.setAccessTokenProvider(accessTokenProvider);
}
Also used : DefaultResponseErrorHandler(org.springframework.web.client.DefaultResponseErrorHandler) DefaultResponseErrorHandler(org.springframework.web.client.DefaultResponseErrorHandler) ResponseErrorHandler(org.springframework.web.client.ResponseErrorHandler) ResponseExtractor(org.springframework.web.client.ResponseExtractor) IOException(java.io.IOException) ResourceAccessException(org.springframework.web.client.ResourceAccessException) ResponseEntity(org.springframework.http.ResponseEntity) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) AuthorizationCodeAccessTokenProvider(org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) BeforeOAuth2Context(org.springframework.security.oauth2.client.test.BeforeOAuth2Context)

Example 38 with OAuth2AccessToken

use of org.springframework.security.oauth2.common.OAuth2AccessToken in project spring-security-oauth by spring-projects.

the class RefreshTokenSupportTests method verifyAccessTokens.

protected void verifyAccessTokens(OAuth2AccessToken oldAccessToken, OAuth2AccessToken newAccessToken) {
    // make sure the new access token can be used.
    verifyTokenResponse(newAccessToken.getValue(), HttpStatus.OK);
    // the old access token is still valid because there is no state on the server.
    verifyTokenResponse(oldAccessToken.getValue(), HttpStatus.OK);
    JwtTokenStore store = (JwtTokenStore) ReflectionTestUtils.getField(services, "tokenStore");
    OAuth2AccessToken token = store.readAccessToken(oldAccessToken.getValue());
    OAuth2AccessToken refresh = ReflectionTestUtils.invokeMethod(store, "convertAccessToken", oldAccessToken.getRefreshToken().getValue());
    assertEquals(refresh.getExpiration().getTime(), token.getExpiration().getTime() + 100000);
}
Also used : JwtTokenStore(org.springframework.security.oauth2.provider.token.store.JwtTokenStore) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken)

Example 39 with OAuth2AccessToken

use of org.springframework.security.oauth2.common.OAuth2AccessToken in project spring-security-oauth by spring-projects.

the class AccessTokenProviderChain method obtainAccessToken.

public OAuth2AccessToken obtainAccessToken(OAuth2ProtectedResourceDetails resource, AccessTokenRequest request) throws UserRedirectRequiredException, AccessDeniedException {
    OAuth2AccessToken accessToken = null;
    OAuth2AccessToken existingToken = null;
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth instanceof AnonymousAuthenticationToken) {
        if (!resource.isClientOnly()) {
            throw new InsufficientAuthenticationException("Authentication is required to obtain an access token (anonymous not allowed)");
        }
    }
    if (resource.isClientOnly() || (auth != null && auth.isAuthenticated())) {
        existingToken = request.getExistingToken();
        if (existingToken == null && clientTokenServices != null) {
            existingToken = clientTokenServices.getAccessToken(resource, auth);
        }
        if (existingToken != null) {
            if (existingToken.isExpired()) {
                if (clientTokenServices != null) {
                    clientTokenServices.removeAccessToken(resource, auth);
                }
                OAuth2RefreshToken refreshToken = existingToken.getRefreshToken();
                if (refreshToken != null) {
                    accessToken = refreshAccessToken(resource, refreshToken, request);
                }
            } else {
                accessToken = existingToken;
            }
        }
    }
    if (accessToken == null) {
        // looks like we need to try to obtain a new token.
        accessToken = obtainNewAccessTokenInternal(resource, request);
        if (accessToken == null) {
            throw new IllegalStateException("An OAuth 2 access token must be obtained or an exception thrown.");
        }
    }
    if (clientTokenServices != null && (resource.isClientOnly() || auth != null && auth.isAuthenticated())) {
        clientTokenServices.saveAccessToken(resource, auth, accessToken);
    }
    return accessToken;
}
Also used : OAuth2RefreshToken(org.springframework.security.oauth2.common.OAuth2RefreshToken) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) Authentication(org.springframework.security.core.Authentication) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) InsufficientAuthenticationException(org.springframework.security.authentication.InsufficientAuthenticationException)

Example 40 with OAuth2AccessToken

use of org.springframework.security.oauth2.common.OAuth2AccessToken in project spring-security-oauth by spring-projects.

the class DefaultOAuth2RequestAuthenticator method authenticate.

@Override
public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext, ClientHttpRequest request) {
    OAuth2AccessToken accessToken = clientContext.getAccessToken();
    if (accessToken == null) {
        throw new AccessTokenRequiredException(resource);
    }
    String tokenType = accessToken.getTokenType();
    if (!StringUtils.hasText(tokenType)) {
        // we'll assume basic bearer token type if none is specified.
        tokenType = OAuth2AccessToken.BEARER_TYPE;
    }
    request.getHeaders().set("Authorization", String.format("%s %s", tokenType, accessToken.getValue()));
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) AccessTokenRequiredException(org.springframework.security.oauth2.client.http.AccessTokenRequiredException)

Aggregations

OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)173 Test (org.junit.Test)126 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)112 OAuth2Authentication (org.springframework.security.oauth2.provider.OAuth2Authentication)66 Date (java.util.Date)36 TokenRequest (org.springframework.security.oauth2.provider.TokenRequest)31 Authentication (org.springframework.security.core.Authentication)27 HashMap (java.util.HashMap)22 DefaultExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken)19 DefaultOAuth2RefreshToken (org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken)18 OAuth2Request (org.springframework.security.oauth2.provider.OAuth2Request)18 DBUnitTest (org.orcid.test.DBUnitTest)17 ExpiringOAuth2RefreshToken (org.springframework.security.oauth2.common.ExpiringOAuth2RefreshToken)17 OAuth2RefreshToken (org.springframework.security.oauth2.common.OAuth2RefreshToken)16 OrcidOauth2TokenDetail (org.orcid.persistence.jpa.entities.OrcidOauth2TokenDetail)11 AuthorizationRequest (org.springframework.security.oauth2.provider.AuthorizationRequest)10 ClientDetails (org.springframework.security.oauth2.provider.ClientDetails)10 Transactional (org.springframework.transaction.annotation.Transactional)10 TokenGranter (org.springframework.security.oauth2.provider.TokenGranter)9 ModelAndView (org.springframework.web.servlet.ModelAndView)9