Search in sources :

Example 11 with UserRedirectRequiredException

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

the class UserInfoTokenServicesTests method badToken.

@Test
public void badToken() {
    this.services.setRestTemplate(this.template);
    given(this.template.getForEntity(any(String.class), eq(Map.class))).willThrow(new UserRedirectRequiredException("foo:bar", Collections.<String, String>emptyMap()));
    this.expected.expect(InvalidTokenException.class);
    assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("unknown");
}
Also used : LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException) Test(org.junit.Test)

Example 12 with UserRedirectRequiredException

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

the class AuthorizationCodeGrantTests method testCannotConnectWithoutToken.

@Test
public void testCannotConnectWithoutToken() throws Exception {
    OAuth2RestTemplate template = new OAuth2RestTemplate(resource);
    resource.setPreEstablishedRedirectUri("http://anywhere.com");
    try {
        template.getForObject(serverRunning.getUrl("/tonr2/photos"), String.class);
        fail("Expected UserRedirectRequiredException");
    } catch (UserRedirectRequiredException e) {
        String message = e.getMessage();
        assertTrue("Wrong message: " + message, message.contains("A redirect is required to get the users approval"));
    }
}
Also used : OAuth2RestTemplate(org.springframework.security.oauth2.client.OAuth2RestTemplate) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException) Test(org.junit.Test)

Example 13 with UserRedirectRequiredException

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

the class OAuth2ClientContextFilter method doFilter.

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    request.setAttribute(CURRENT_URI, calculateCurrentUri(request));
    try {
        chain.doFilter(servletRequest, servletResponse);
    } catch (IOException ex) {
        throw ex;
    } catch (Exception ex) {
        // Try to extract a SpringSecurityException from the stacktrace
        Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
        UserRedirectRequiredException redirect = (UserRedirectRequiredException) throwableAnalyzer.getFirstThrowableOfType(UserRedirectRequiredException.class, causeChain);
        if (redirect != null) {
            redirectUser(redirect, request, response);
        } else {
            if (ex instanceof ServletException) {
                throw (ServletException) ex;
            }
            if (ex instanceof RuntimeException) {
                throw (RuntimeException) ex;
            }
            throw new NestedServletException("Unhandled exception", ex);
        }
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) NestedServletException(org.springframework.web.util.NestedServletException) NestedServletException(org.springframework.web.util.NestedServletException) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException) NestedServletException(org.springframework.web.util.NestedServletException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException)

Example 14 with UserRedirectRequiredException

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

the class AuthorizationCodeAccessTokenProvider method getRedirectForAuthorization.

private UserRedirectRequiredException getRedirectForAuthorization(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {
    // we don't have an authorization code yet. So first get that.
    TreeMap<String, String> requestParameters = new TreeMap<String, String>();
    // oauth2 spec, section 3
    requestParameters.put("response_type", "code");
    requestParameters.put("client_id", resource.getClientId());
    // Client secret is not required in the initial authorization request
    String redirectUri = resource.getRedirectUri(request);
    if (redirectUri != null) {
        requestParameters.put("redirect_uri", redirectUri);
    }
    if (resource.isScoped()) {
        StringBuilder builder = new StringBuilder();
        List<String> scope = resource.getScope();
        if (scope != null) {
            Iterator<String> scopeIt = scope.iterator();
            while (scopeIt.hasNext()) {
                builder.append(scopeIt.next());
                if (scopeIt.hasNext()) {
                    builder.append(' ');
                }
            }
        }
        requestParameters.put("scope", builder.toString());
    }
    UserRedirectRequiredException redirectException = new UserRedirectRequiredException(resource.getUserAuthorizationUri(), requestParameters);
    String stateKey = stateKeyGenerator.generateKey(resource);
    redirectException.setStateKey(stateKey);
    request.setStateKey(stateKey);
    redirectException.setStateToPreserve(redirectUri);
    request.setPreservedState(redirectUri);
    return redirectException;
}
Also used : TreeMap(java.util.TreeMap) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException)

Example 15 with UserRedirectRequiredException

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

the class AuthorizationCodeAccessTokenProvider method obtainAuthorizationCode.

public String obtainAuthorizationCode(OAuth2ProtectedResourceDetails details, AccessTokenRequest request) throws UserRedirectRequiredException, UserApprovalRequiredException, AccessDeniedException, OAuth2AccessDeniedException {
    AuthorizationCodeResourceDetails resource = (AuthorizationCodeResourceDetails) details;
    HttpHeaders headers = getHeadersForAuthorizationRequest(request);
    MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>();
    if (request.containsKey(OAuth2Utils.USER_OAUTH_APPROVAL)) {
        form.set(OAuth2Utils.USER_OAUTH_APPROVAL, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        for (String scope : details.getScope()) {
            form.set(scopePrefix + scope, request.getFirst(OAuth2Utils.USER_OAUTH_APPROVAL));
        }
    } else {
        form.putAll(getParametersForAuthorizeRequest(resource, request));
    }
    authorizationRequestEnhancer.enhance(request, resource, form, headers);
    final AccessTokenRequest copy = request;
    final ResponseExtractor<ResponseEntity<Void>> delegate = getAuthorizationResponseExtractor();
    ResponseExtractor<ResponseEntity<Void>> extractor = new ResponseExtractor<ResponseEntity<Void>>() {

        @Override
        public ResponseEntity<Void> extractData(ClientHttpResponse response) throws IOException {
            if (response.getHeaders().containsKey("Set-Cookie")) {
                copy.setCookie(response.getHeaders().getFirst("Set-Cookie"));
            }
            return delegate.extractData(response);
        }
    };
    // Instead of using restTemplate.exchange we use an explicit response extractor here so it can be overridden by
    // subclasses
    ResponseEntity<Void> response = getRestTemplate().execute(resource.getUserAuthorizationUri(), HttpMethod.POST, getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap());
    if (response.getStatusCode() == HttpStatus.OK) {
        // Need to re-submit with approval...
        throw getUserApprovalSignal(resource, request);
    }
    URI location = response.getHeaders().getLocation();
    String query = location.getQuery();
    Map<String, String> map = OAuth2Utils.extractMap(query);
    if (map.containsKey("state")) {
        request.setStateKey(map.get("state"));
        if (request.getPreservedState() == null) {
            String redirectUri = resource.getRedirectUri(request);
            if (redirectUri != null) {
                request.setPreservedState(redirectUri);
            } else {
                request.setPreservedState(new Object());
            }
        }
    }
    String code = map.get("code");
    if (code == null) {
        throw new UserRedirectRequiredException(location.toString(), form.toSingleValueMap());
    }
    request.set("code", code);
    return code;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) ResponseExtractor(org.springframework.web.client.ResponseExtractor) URI(java.net.URI) UserRedirectRequiredException(org.springframework.security.oauth2.client.resource.UserRedirectRequiredException) ResponseEntity(org.springframework.http.ResponseEntity) AccessTokenRequest(org.springframework.security.oauth2.client.token.AccessTokenRequest) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

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