Search in sources :

Example 41 with OAuth2AccessToken

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

the class OAuth2RestTemplate method acquireAccessToken.

protected OAuth2AccessToken acquireAccessToken(OAuth2ClientContext oauth2Context) throws UserRedirectRequiredException {
    AccessTokenRequest accessTokenRequest = oauth2Context.getAccessTokenRequest();
    if (accessTokenRequest == null) {
        throw new AccessTokenRequiredException("No OAuth 2 security context has been established. Unable to access resource '" + this.resource.getId() + "'.", resource);
    }
    // Transfer the preserved state from the (longer lived) context to the current request.
    String stateKey = accessTokenRequest.getStateKey();
    if (stateKey != null) {
        accessTokenRequest.setPreservedState(oauth2Context.removePreservedState(stateKey));
    }
    OAuth2AccessToken existingToken = oauth2Context.getAccessToken();
    if (existingToken != null) {
        accessTokenRequest.setExistingToken(existingToken);
    }
    OAuth2AccessToken accessToken = null;
    accessToken = accessTokenProvider.obtainAccessToken(resource, accessTokenRequest);
    if (accessToken == null || accessToken.getValue() == null) {
        throw new IllegalStateException("Access token provider returned a null access token, which is illegal according to the contract.");
    }
    oauth2Context.setAccessToken(accessToken);
    return accessToken;
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) AccessTokenRequiredException(org.springframework.security.oauth2.client.http.AccessTokenRequiredException) AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest)

Example 42 with OAuth2AccessToken

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

the class AdminController method enhance.

private Collection<OAuth2AccessToken> enhance(Collection<OAuth2AccessToken> tokens) {
    Collection<OAuth2AccessToken> result = new ArrayList<OAuth2AccessToken>();
    for (OAuth2AccessToken prototype : tokens) {
        DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken(prototype);
        OAuth2Authentication authentication = tokenStore.readAuthentication(token);
        if (authentication == null) {
            continue;
        }
        String clientId = authentication.getOAuth2Request().getClientId();
        if (clientId != null) {
            Map<String, Object> map = new HashMap<String, Object>(token.getAdditionalInformation());
            map.put("client_id", clientId);
            token.setAdditionalInformation(map);
            result.add(token);
        }
    }
    return result;
}
Also used : HashMap(java.util.HashMap) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2Authentication(org.springframework.security.oauth2.provider.OAuth2Authentication) ArrayList(java.util.ArrayList) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)

Example 43 with OAuth2AccessToken

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

the class AdminEndpointsTests method testRevokeTokenByUser.

@Test
@OAuth2ContextConfiguration(ResourceOwnerWriteOnly.class)
public void testRevokeTokenByUser() throws Exception {
    OAuth2AccessToken token = context.getAccessToken();
    String tokenValueBeforeDeletion = token.getValue();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<?> request = new HttpEntity<Void>(headers);
    assertEquals(HttpStatus.NO_CONTENT, serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/sparklr2/oauth/users/{user}/tokens/{token}"), HttpMethod.DELETE, request, Void.class, "marissa", token.getValue()).getStatusCode());
    try {
        // The request above will delete the oauth token so that the next request will initially fail. However,
        // the failure will be detected and a new access token will be obtained.  The new access token
        // only has "write" scope and the requested resource needs "read" scope.  So, an insufficient_scope
        // exception should be thrown.
        ResponseEntity<String> result = serverRunning.getForString("/sparklr2/oauth/clients/my-client-with-registered-redirect/users/marissa/tokens", headers);
        fail("Should have thrown an exception");
        assertNotNull(result);
    } catch (InsufficientScopeException ex) {
        assertEquals(HttpStatus.FORBIDDEN.value(), ex.getHttpErrorCode());
        assertEquals("insufficient_scope", ex.getOAuth2ErrorCode());
        String secondTokenWithWriteOnlyScope = context.getOAuth2ClientContext().getAccessToken().getValue();
        assertNotNull(secondTokenWithWriteOnlyScope);
        assertFalse(secondTokenWithWriteOnlyScope.equals(tokenValueBeforeDeletion));
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) InsufficientScopeException(org.springframework.security.oauth2.common.exceptions.InsufficientScopeException) HttpEntity(org.springframework.http.HttpEntity) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) OAuth2ContextConfiguration(org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration) Test(org.junit.Test)

Example 44 with OAuth2AccessToken

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

the class AuthorizationCodeProviderTests 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 {
                    response.getHeaders();
                    response.getStatusCode();
                    tokenEndpointResponse = response;
                    return extractor.extractData(response);
                }
            };
        }

        @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 : ResponseEntity(org.springframework.http.ResponseEntity) DefaultResponseErrorHandler(org.springframework.web.client.DefaultResponseErrorHandler) DefaultResponseErrorHandler(org.springframework.web.client.DefaultResponseErrorHandler) ResponseErrorHandler(org.springframework.web.client.ResponseErrorHandler) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) AuthorizationCodeAccessTokenProvider(org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider) ResponseExtractor(org.springframework.web.client.ResponseExtractor) IOException(java.io.IOException) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) BeforeOAuth2Context(org.springframework.security.oauth2.client.test.BeforeOAuth2Context)

Example 45 with OAuth2AccessToken

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

the class AuthorizationCodeGrantTests method testAttemptedTokenAcquisitionWithNoRedirect.

@Test
public void testAttemptedTokenAcquisitionWithNoRedirect() throws Exception {
    AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider();
    try {
        OAuth2AccessToken token = provider.obtainAccessToken(resource, new DefaultAccessTokenRequest());
        fail("Expected UserRedirectRequiredException");
        assertNotNull(token);
    } catch (UserRedirectRequiredException e) {
        String message = e.getMessage();
        assertTrue("Wrong message: " + message, message.contains("A redirect is required"));
    }
}
Also used : OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) AuthorizationCodeAccessTokenProvider(org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeAccessTokenProvider) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException) DefaultAccessTokenRequest(org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest) Test(org.junit.Test)

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