Search in sources :

Example 6 with UserRedirectRequiredException

use of org.springframework.security.oauth2.client.resource.UserRedirectRequiredException 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 7 with UserRedirectRequiredException

use of org.springframework.security.oauth2.client.resource.UserRedirectRequiredException 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 8 with UserRedirectRequiredException

use of org.springframework.security.oauth2.client.resource.UserRedirectRequiredException in project spring-security-oauth by spring-projects.

the class AuthorizationCodeProviderTests method testUnauthenticatedAuthorizationRequestRedirectsToLogin.

@Test
@OAuth2ContextConfiguration(resource = MyLessTrustedClient.class, initialize = false)
public void testUnauthenticatedAuthorizationRequestRedirectsToLogin() throws Exception {
    AccessTokenRequest request = context.getAccessTokenRequest();
    request.setCurrentUri("http://anywhere");
    request.add(OAuth2Utils.USER_OAUTH_APPROVAL, "true");
    String location = null;
    try {
        String code = accessTokenProvider.obtainAuthorizationCode(context.getResource(), request);
        assertNotNull(code);
        fail("Expected UserRedirectRequiredException");
    } catch (UserRedirectRequiredException e) {
        location = e.getRedirectUri();
    }
    assertNotNull(location);
    assertEquals(serverRunning.getUrl("/sparklr2/login.jsp"), location);
}
Also used : AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException) OAuth2ContextConfiguration(org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration) Test(org.junit.Test)

Example 9 with UserRedirectRequiredException

use of org.springframework.security.oauth2.client.resource.UserRedirectRequiredException 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)

Example 10 with UserRedirectRequiredException

use of org.springframework.security.oauth2.client.resource.UserRedirectRequiredException in project spring-security-oauth by spring-projects.

the class AuthorizationCodeProviderTests method approveAccessTokenGrant.

private void approveAccessTokenGrant(String currentUri, boolean approved) {
    AccessTokenRequest request = context.getAccessTokenRequest();
    AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) context.getResource();
    request.setCookie(cookie);
    if (currentUri != null) {
        request.setCurrentUri(currentUri);
    }
    String location = null;
    try {
        // First try to obtain the access token...
        assertNotNull(context.getAccessToken());
        fail("Expected UserRedirectRequiredException");
    } catch (UserRedirectRequiredException e) {
        // Expected and necessary, so that the correct state is set up in the request...
        location = e.getRedirectUri();
    }
    assertTrue(location.startsWith(resource.getUserAuthorizationUri()));
    assertNull(request.getAuthorizationCode());
    try {
        // Now try again and the token provider will redirect for user approval...
        assertNotNull(context.getAccessToken());
        fail("Expected UserRedirectRequiredException");
    } catch (UserApprovalRequiredException e) {
        // Expected and necessary, so that the user can approve the grant...
        location = e.getApprovalUri();
    }
    assertTrue(location.startsWith(resource.getUserAuthorizationUri()));
    assertNull(request.getAuthorizationCode());
    // The approval (will be processed on the next attempt to obtain an access token)...
    request.set(OAuth2Utils.USER_OAUTH_APPROVAL, "" + approved);
}
Also used : UserApprovalRequiredException(org.springframework.security.oauth2.client.resource.UserApprovalRequiredException) AuthorizationCodeResourceDetails(org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails) AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException)

Aggregations

UserRedirectRequiredException (org.springframework.security.oauth2.client.resource.UserRedirectRequiredException)15 Test (org.junit.Test)9 AccessTokenRequest (org.springframework.security.oauth2.client.token.AccessTokenRequest)9 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)5 UserApprovalRequiredException (org.springframework.security.oauth2.client.resource.UserApprovalRequiredException)3 OAuth2ContextConfiguration (org.springframework.security.oauth2.client.test.OAuth2ContextConfiguration)3 AuthorizationCodeResourceDetails (org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails)3 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)3 HttpHeaders (org.springframework.http.HttpHeaders)2 BaseOAuth2ProtectedResourceDetails (org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails)2 OAuth2ProtectedResourceDetails (org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails)2 DefaultAccessTokenRequest (org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 Date (java.util.Date)1 LinkedHashMap (java.util.LinkedHashMap)1 Map (java.util.Map)1 TreeMap (java.util.TreeMap)1 ServletException (javax.servlet.ServletException)1