Search in sources :

Example 11 with OAuth2ProtectedResourceDetails

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

the class OAuth2AccessTokenSupport method retrieveToken.

protected OAuth2AccessToken retrieveToken(AccessTokenRequest request, OAuth2ProtectedResourceDetails resource, MultiValueMap<String, String> form, HttpHeaders headers) throws OAuth2AccessDeniedException {
    try {
        // Prepare headers and form before going into rest template call in case the URI is affected by the result
        authenticationHandler.authenticateTokenRequest(resource, form, headers);
        // Opportunity to customize form and headers
        tokenRequestEnhancer.enhance(request, resource, form, headers);
        final AccessTokenRequest copy = request;
        final ResponseExtractor<OAuth2AccessToken> delegate = getResponseExtractor();
        ResponseExtractor<OAuth2AccessToken> extractor = new ResponseExtractor<OAuth2AccessToken>() {

            @Override
            public OAuth2AccessToken extractData(ClientHttpResponse response) throws IOException {
                if (response.getHeaders().containsKey("Set-Cookie")) {
                    copy.setCookie(response.getHeaders().getFirst("Set-Cookie"));
                }
                return delegate.extractData(response);
            }
        };
        return getRestTemplate().execute(getAccessTokenUri(resource, form), getHttpMethod(), getRequestCallback(resource, form, headers), extractor, form.toSingleValueMap());
    } catch (OAuth2Exception oe) {
        throw new OAuth2AccessDeniedException("Access token denied.", resource, oe);
    } catch (RestClientException rce) {
        throw new OAuth2AccessDeniedException("Error requesting access token.", resource, rce);
    }
}
Also used : OAuth2AccessDeniedException(org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException) OAuth2AccessToken(org.springframework.security.oauth2.common.OAuth2AccessToken) RestClientException(org.springframework.web.client.RestClientException) ResponseExtractor(org.springframework.web.client.ResponseExtractor) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) OAuth2Exception(org.springframework.security.oauth2.common.exceptions.OAuth2Exception)

Example 12 with OAuth2ProtectedResourceDetails

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

the class DefaultClientAuthenticationHandler method authenticateTokenRequest.

public void authenticateTokenRequest(OAuth2ProtectedResourceDetails resource, MultiValueMap<String, String> form, HttpHeaders headers) {
    if (resource.isAuthenticationRequired()) {
        AuthenticationScheme scheme = AuthenticationScheme.header;
        if (resource.getClientAuthenticationScheme() != null) {
            scheme = resource.getClientAuthenticationScheme();
        }
        try {
            String clientSecret = resource.getClientSecret();
            clientSecret = clientSecret == null ? "" : clientSecret;
            switch(scheme) {
                case header:
                    form.remove("client_secret");
                    headers.add("Authorization", String.format("Basic %s", new String(Base64.encode(String.format("%s:%s", resource.getClientId(), clientSecret).getBytes("UTF-8")), "UTF-8")));
                    break;
                case form:
                case query:
                    form.set("client_id", resource.getClientId());
                    if (StringUtils.hasText(clientSecret)) {
                        form.set("client_secret", clientSecret);
                    }
                    break;
                default:
                    throw new IllegalStateException("Default authentication handler doesn't know how to handle scheme: " + scheme);
            }
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
    }
}
Also used : AuthenticationScheme(org.springframework.security.oauth2.common.AuthenticationScheme) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 13 with OAuth2ProtectedResourceDetails

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

Example 14 with OAuth2ProtectedResourceDetails

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

the class OAuth2RestTemplateTests method testCustomAuthenticator.

@Test
public void testCustomAuthenticator() throws Exception {
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken("12345");
    token.setTokenType("MINE");
    restTemplate.setAuthenticator(new OAuth2RequestAuthenticator() {

        @Override
        public void authenticate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext clientContext, ClientHttpRequest req) {
            req.getHeaders().set("X-Authorization", clientContext.getAccessToken().getTokenType() + " " + "Nah-nah-na-nah-nah");
        }
    });
    restTemplate.getOAuth2ClientContext().setAccessToken(token);
    ClientHttpRequest http = restTemplate.createRequest(URI.create("https://nowhere.com/api/crap"), HttpMethod.GET);
    String auth = http.getHeaders().getFirst("X-Authorization");
    assertEquals("MINE Nah-nah-na-nah-nah", auth);
}
Also used : BaseOAuth2ProtectedResourceDetails(org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails) OAuth2ProtectedResourceDetails(org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Test(org.junit.Test)

Example 15 with OAuth2ProtectedResourceDetails

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

the class UserInfoTokenServicesRefreshTokenTests method withRestTemplate.

@Test
public void withRestTemplate() {
    OAuth2ProtectedResourceDetails resource = new AuthorizationCodeResourceDetails();
    OAuth2ClientContext context = new DefaultOAuth2ClientContext();
    DefaultOAuth2AccessToken token = new DefaultOAuth2AccessToken("FOO");
    token.setRefreshToken(new DefaultExpiringOAuth2RefreshToken("BAR", new Date(0L)));
    context.setAccessToken(token);
    this.services.setRestTemplate(new OAuth2RestTemplate(resource, context));
    assertThat(this.services.loadAuthentication("FOO").getName()).isEqualTo("me");
    assertThat(context.getAccessToken().getValue()).isEqualTo("FOO");
    // The refresh token is still intact
    assertThat(context.getAccessToken().getRefreshToken()).isEqualTo(token.getRefreshToken());
}
Also used : DefaultOAuth2ClientContext(org.springframework.security.oauth2.client.DefaultOAuth2ClientContext) DefaultOAuth2ClientContext(org.springframework.security.oauth2.client.DefaultOAuth2ClientContext) OAuth2ClientContext(org.springframework.security.oauth2.client.OAuth2ClientContext) OAuth2ProtectedResourceDetails(org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails) AuthorizationCodeResourceDetails(org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails) DefaultExpiringOAuth2RefreshToken(org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken) OAuth2RestTemplate(org.springframework.security.oauth2.client.OAuth2RestTemplate) DefaultOAuth2AccessToken(org.springframework.security.oauth2.common.DefaultOAuth2AccessToken) Date(java.util.Date) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Aggregations

OAuth2ProtectedResourceDetails (org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails)6 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)6 Test (org.junit.Test)5 AuthorizationCodeResourceDetails (org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails)5 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)5 OAuth2RestTemplate (org.springframework.security.oauth2.client.OAuth2RestTemplate)4 Bean (org.springframework.context.annotation.Bean)3 ClientHttpResponse (org.springframework.http.client.ClientHttpResponse)3 DefaultOAuth2ClientContext (org.springframework.security.oauth2.client.DefaultOAuth2ClientContext)3 OAuth2ClientContext (org.springframework.security.oauth2.client.OAuth2ClientContext)3 BaseOAuth2ProtectedResourceDetails (org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails)3 UserRedirectRequiredException (org.springframework.security.oauth2.client.resource.UserRedirectRequiredException)3 AccessTokenRequest (org.springframework.security.oauth2.client.token.AccessTokenRequest)3 Date (java.util.Date)2 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)2 ResponseExtractor (org.springframework.web.client.ResponseExtractor)2 IOException (java.io.IOException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 AssumptionViolatedException (org.junit.internal.AssumptionViolatedException)1