Search in sources :

Example 36 with OAuth2AuthorizationExchange

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange in project spring-security by spring-projects.

the class NimbusAuthorizationCodeTokenResponseClientTests method setUp.

@BeforeEach
public void setUp() {
    this.clientRegistrationBuilder = TestClientRegistrations.clientRegistration().clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
    this.authorizationRequest = TestOAuth2AuthorizationRequests.request().build();
    this.authorizationResponse = TestOAuth2AuthorizationResponses.success().build();
    this.authorizationExchange = new OAuth2AuthorizationExchange(this.authorizationRequest, this.authorizationResponse);
}
Also used : OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 37 with OAuth2AuthorizationExchange

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange in project spring-security by spring-projects.

the class NimbusAuthorizationCodeTokenResponseClientTests method getTokenResponseWhenRedirectUriMalformedThenThrowIllegalArgumentException.

@Test
public void getTokenResponseWhenRedirectUriMalformedThenThrowIllegalArgumentException() {
    String redirectUri = "http:\\example.com";
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().redirectUri(redirectUri).build();
    OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, this.authorizationResponse);
    assertThatIllegalArgumentException().isThrownBy(() -> this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(this.clientRegistrationBuilder.build(), authorizationExchange)));
}
Also used : OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 38 with OAuth2AuthorizationExchange

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange in project spring-security by spring-projects.

the class NimbusAuthorizationCodeTokenResponseClientTests method getTokenResponseWhenSuccessResponseIncludesScopeThenReturnAccessTokenResponseUsingResponseScope.

@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenReturnAccessTokenResponseUsingResponseScope() throws Exception {
    MockWebServer server = new MockWebServer();
    // @formatter:off
    String accessTokenSuccessResponse = "{\n" + "   \"access_token\": \"access-token-1234\",\n" + "   \"token_type\": \"bearer\",\n" + "   \"expires_in\": \"3600\",\n" + "   \"scope\": \"openid profile\"\n" + "}\n";
    // @formatter:on
    server.enqueue(new MockResponse().setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(accessTokenSuccessResponse));
    server.start();
    String tokenUri = server.url("/oauth2/token").toString();
    this.clientRegistrationBuilder.tokenUri(tokenUri);
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().scope("openid", "profile", "email", "address").build();
    OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, this.authorizationResponse);
    OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(new OAuth2AuthorizationCodeGrantRequest(this.clientRegistrationBuilder.build(), authorizationExchange));
    server.shutdown();
    assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("openid", "profile");
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) MockResponse(okhttp3.mockwebserver.MockResponse) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) MockWebServer(okhttp3.mockwebserver.MockWebServer) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 39 with OAuth2AuthorizationExchange

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeGrantFilter method processAuthorizationResponse.

private void processAuthorizationResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
    OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.removeAuthorizationRequest(request, response);
    String registrationId = authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID);
    ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
    MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
    String redirectUri = UrlUtils.buildFullRequestUrl(request);
    OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params, redirectUri);
    OAuth2AuthorizationCodeAuthenticationToken authenticationRequest = new OAuth2AuthorizationCodeAuthenticationToken(clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
    authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    OAuth2AuthorizationCodeAuthenticationToken authenticationResult;
    try {
        authenticationResult = (OAuth2AuthorizationCodeAuthenticationToken) this.authenticationManager.authenticate(authenticationRequest);
    } catch (OAuth2AuthorizationException ex) {
        OAuth2Error error = ex.getError();
        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(authorizationRequest.getRedirectUri()).queryParam(OAuth2ParameterNames.ERROR, error.getErrorCode());
        if (!StringUtils.isEmpty(error.getDescription())) {
            uriBuilder.queryParam(OAuth2ParameterNames.ERROR_DESCRIPTION, error.getDescription());
        }
        if (!StringUtils.isEmpty(error.getUri())) {
            uriBuilder.queryParam(OAuth2ParameterNames.ERROR_URI, error.getUri());
        }
        this.redirectStrategy.sendRedirect(request, response, uriBuilder.build().encode().toString());
        return;
    }
    Authentication currentAuthentication = SecurityContextHolder.getContext().getAuthentication();
    String principalName = (currentAuthentication != null) ? currentAuthentication.getName() : "anonymousUser";
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(authenticationResult.getClientRegistration(), principalName, authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
    this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, currentAuthentication, request, response);
    String redirectUrl = authorizationRequest.getRedirectUri();
    SavedRequest savedRequest = this.requestCache.getRequest(request, response);
    if (savedRequest != null) {
        redirectUrl = savedRequest.getRedirectUrl();
        this.requestCache.removeRequest(request, response);
    }
    this.redirectStrategy.sendRedirect(request, response, redirectUrl);
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) UriComponentsBuilder(org.springframework.web.util.UriComponentsBuilder) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) SavedRequest(org.springframework.security.web.savedrequest.SavedRequest)

Example 40 with OAuth2AuthorizationExchange

use of org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationFilter method attemptAuthentication.

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    MultiValueMap<String, String> params = OAuth2AuthorizationResponseUtils.toMultiMap(request.getParameterMap());
    if (!OAuth2AuthorizationResponseUtils.isAuthorizationResponse(params)) {
        OAuth2Error oauth2Error = new OAuth2Error(OAuth2ErrorCodes.INVALID_REQUEST);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestRepository.removeAuthorizationRequest(request, response);
    if (authorizationRequest == null) {
        OAuth2Error oauth2Error = new OAuth2Error(AUTHORIZATION_REQUEST_NOT_FOUND_ERROR_CODE);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    String registrationId = authorizationRequest.getAttribute(OAuth2ParameterNames.REGISTRATION_ID);
    ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId);
    if (clientRegistration == null) {
        OAuth2Error oauth2Error = new OAuth2Error(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE, "Client Registration not found with Id: " + registrationId, null);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    // @formatter:off
    String redirectUri = UriComponentsBuilder.fromHttpUrl(UrlUtils.buildFullRequestUrl(request)).replaceQuery(null).build().toUriString();
    // @formatter:on
    OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params, redirectUri);
    Object authenticationDetails = this.authenticationDetailsSource.buildDetails(request);
    OAuth2LoginAuthenticationToken authenticationRequest = new OAuth2LoginAuthenticationToken(clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
    authenticationRequest.setDetails(authenticationDetails);
    OAuth2LoginAuthenticationToken authenticationResult = (OAuth2LoginAuthenticationToken) this.getAuthenticationManager().authenticate(authenticationRequest);
    OAuth2AuthenticationToken oauth2Authentication = this.authenticationResultConverter.convert(authenticationResult);
    Assert.notNull(oauth2Authentication, "authentication result cannot be null");
    oauth2Authentication.setDetails(authenticationDetails);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(authenticationResult.getClientRegistration(), oauth2Authentication.getName(), authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
    this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, oauth2Authentication, request, response);
    return oauth2Authentication;
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)

Aggregations

OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)44 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)26 Test (org.junit.jupiter.api.Test)24 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)23 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)19 OAuth2AuthorizationCodeAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken)10 HashMap (java.util.HashMap)9 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)9 OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)8 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)8 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)7 ServerAuthenticationConverter (org.springframework.security.web.server.authentication.ServerAuthenticationConverter)7 WebTestClient (org.springframework.test.web.reactive.server.WebTestClient)7 BeforeEach (org.junit.jupiter.api.BeforeEach)5 HttpHeaders (org.springframework.http.HttpHeaders)5 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)5 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)4 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)4 BDDMockito.given (org.mockito.BDDMockito.given)4 Mockito.mock (org.mockito.Mockito.mock)4