Search in sources :

Example 16 with OAuth2AuthorizationException

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenAuthorizationExceptionThenInvokeFailureHandler.

@Test
public void filterWhenAuthorizationExceptionThenInvokeFailureHandler() {
    this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
    PublisherProbe<Void> publisherProbe = PublisherProbe.empty();
    given(this.authorizationFailureHandler.onAuthorizationFailure(any(), any(), any())).willReturn(publisherProbe.mono());
    OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken);
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).build();
    OAuth2AuthorizationException exception = new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN, null, null));
    ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
    assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> this.function.filter(request, throwingExchangeFunction).subscriberContext(serverWebExchange()).block()).isEqualTo(exception);
    assertThat(publisherProbe.wasSubscribed()).isTrue();
    verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture());
    assertThat(this.authorizationExceptionCaptor.getValue()).isSameAs(exception);
    assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
    assertThat(this.attributesCaptor.getValue()).containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) BeforeEach(org.junit.jupiter.api.BeforeEach) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BodyInserter(org.springframework.web.reactive.function.BodyInserter) OAuth2RefreshTokenGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) ReactiveSecurityContextHolder(org.springframework.security.core.context.ReactiveSecurityContextHolder) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) BDDMockito.given(org.mockito.BDDMockito.given) Duration(java.time.Duration) Map(java.util.Map) ServerSentEventHttpMessageWriter(org.springframework.http.codec.ServerSentEventHttpMessageWriter) ReactiveOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizationFailureHandler) URI(java.net.URI) Jwt(org.springframework.security.oauth2.jwt.Jwt) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) HttpHeaders(org.springframework.http.HttpHeaders) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) JwtBearerReactiveOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.JwtBearerReactiveOAuth2AuthorizedClientProvider) Context(reactor.util.context.Context) MediaType(org.springframework.http.MediaType) ReactiveOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProvider) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) OAuth2PasswordGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest) Instant(java.time.Instant) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) PublisherProbe(reactor.test.publisher.PublisherProbe) Test(org.junit.jupiter.api.Test) List(java.util.List) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) Optional(java.util.Optional) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) Authentication(org.springframework.security.core.Authentication) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) MockClientHttpRequest(org.springframework.mock.http.client.reactive.MockClientHttpRequest) ClientAuthorizationException(org.springframework.security.oauth2.client.ClientAuthorizationException) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) MultipartHttpMessageWriter(org.springframework.http.codec.multipart.MultipartHttpMessageWriter) Mock(org.mockito.Mock) ByteBufferEncoder(org.springframework.core.codec.ByteBufferEncoder) ReactiveOAuth2AuthorizedClientProviderBuilder(org.springframework.security.oauth2.client.ReactiveOAuth2AuthorizedClientProviderBuilder) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) HashMap(java.util.HashMap) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) Mockito.spy(org.mockito.Mockito.spy) Captor(org.mockito.Captor) ArrayList(java.util.ArrayList) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) DefaultReactiveOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultReactiveOAuth2AuthorizedClientManager) ArgumentCaptor(org.mockito.ArgumentCaptor) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) UnAuthenticatedServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) HttpMethod(org.springframework.http.HttpMethod) WebClientReactiveClientCredentialsTokenResponseClient(org.springframework.security.oauth2.client.endpoint.WebClientReactiveClientCredentialsTokenResponseClient) Mono(reactor.core.publisher.Mono) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) Assertions.entry(org.assertj.core.api.Assertions.entry) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Mockito.verify(org.mockito.Mockito.verify) HttpStatus(org.springframework.http.HttpStatus) Mockito.never(org.mockito.Mockito.never) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) StringUtils(org.springframework.util.StringUtils) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) Test(org.junit.jupiter.api.Test)

Example 17 with OAuth2AuthorizationException

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenAuthorizationExceptionThenInvokeFailureHandler.

@Test
public void filterWhenAuthorizationExceptionThenInvokeFailureHandler() {
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken);
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)).build();
    OAuth2AuthorizationException authorizationException = new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_TOKEN));
    ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(authorizationException);
    this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
    assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> this.function.filter(request, throwingExchangeFunction).block()).isEqualTo(authorizationException);
    verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture());
    assertThat(this.authorizationExceptionCaptor.getValue()).isInstanceOfSatisfying(OAuth2AuthorizationException.class, (ex) -> {
        assertThat(ex.getError().getErrorCode()).isEqualTo(authorizationException.getError().getErrorCode());
        assertThat(ex).hasNoCause();
        assertThat(ex).hasMessageContaining(OAuth2ErrorCodes.INVALID_TOKEN);
    });
    assertThat(this.authenticationCaptor.getValue().getName()).isEqualTo(authorizedClient.getPrincipalName());
    assertThat(this.attributesCaptor.getValue()).containsExactly(entry(HttpServletRequest.class.getName(), servletRequest), entry(HttpServletResponse.class.getName(), servletResponse));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) CharSequenceEncoder(org.springframework.core.codec.CharSequenceEncoder) BeforeEach(org.junit.jupiter.api.BeforeEach) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) OAuth2RefreshTokenGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2RefreshTokenGrantRequest) RequestContextHolder(org.springframework.web.context.request.RequestContextHolder) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) DefaultClientCredentialsTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultClientCredentialsTokenResponseClient) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) Duration(java.time.Duration) Map(java.util.Map) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) FormHttpMessageWriter(org.springframework.http.codec.FormHttpMessageWriter) Context(reactor.util.context.Context) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuth2PasswordGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2PasswordGrantRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) MockClientHttpRequest(org.springframework.mock.http.client.reactive.MockClientHttpRequest) Mockito.mock(org.mockito.Mockito.mock) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Mock(org.mockito.Mock) DefaultRefreshTokenTokenResponseClient(org.springframework.security.oauth2.client.endpoint.DefaultRefreshTokenTokenResponseClient) JwtBearerOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.JwtBearerOAuth2AuthorizedClientProvider) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ArrayList(java.util.ArrayList) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) RequestEntity(org.springframework.http.RequestEntity) OAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler) HttpMethod(org.springframework.http.HttpMethod) Mono(reactor.core.publisher.Mono) RestOperations(org.springframework.web.client.RestOperations) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) HttpStatus(org.springframework.http.HttpStatus) AfterEach(org.junit.jupiter.api.AfterEach) OAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository) Mockito.never(org.mockito.Mockito.never) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) HttpMessageWriter(org.springframework.http.codec.HttpMessageWriter) AuthorizationGrantType(org.springframework.security.oauth2.core.AuthorizationGrantType) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) WebClient(org.springframework.web.reactive.function.client.WebClient) BodyInserter(org.springframework.web.reactive.function.BodyInserter) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) ServerSentEventHttpMessageWriter(org.springframework.http.codec.ServerSentEventHttpMessageWriter) URI(java.net.URI) Jwt(org.springframework.security.oauth2.jwt.Jwt) ServerHttpRequest(org.springframework.http.server.reactive.ServerHttpRequest) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) HttpHeaders(org.springframework.http.HttpHeaders) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test) List(java.util.List) Optional(java.util.Optional) Authentication(org.springframework.security.core.Authentication) OAuth2ClientCredentialsGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2ClientCredentialsGrantRequest) ClientAuthorizationException(org.springframework.security.oauth2.client.ClientAuthorizationException) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) RefreshTokenOAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.RefreshTokenOAuth2AuthorizedClientProvider) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) MultipartHttpMessageWriter(org.springframework.http.codec.multipart.MultipartHttpMessageWriter) ByteBufferEncoder(org.springframework.core.codec.ByteBufferEncoder) ResourceHttpMessageWriter(org.springframework.http.codec.ResourceHttpMessageWriter) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) HashMap(java.util.HashMap) Jackson2JsonEncoder(org.springframework.http.codec.json.Jackson2JsonEncoder) Captor(org.mockito.Captor) ArgumentCaptor(org.mockito.ArgumentCaptor) EncoderHttpMessageWriter(org.springframework.http.codec.EncoderHttpMessageWriter) ClientAuthenticationMethod(org.springframework.security.oauth2.core.ClientAuthenticationMethod) JwtBearerGrantRequest(org.springframework.security.oauth2.client.endpoint.JwtBearerGrantRequest) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) TestOAuth2AccessTokenResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AccessTokenResponses) OAuth2AuthorizedClientProviderBuilder(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) Assertions.entry(org.assertj.core.api.Assertions.entry) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Mockito.verify(org.mockito.Mockito.verify) Consumer(java.util.function.Consumer) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) DefaultOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager) ResponseEntity(org.springframework.http.ResponseEntity) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) StringUtils(org.springframework.util.StringUtils) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) ExchangeFunction(org.springframework.web.reactive.function.client.ExchangeFunction) Test(org.junit.jupiter.api.Test)

Example 18 with OAuth2AuthorizationException

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

the class DefaultOAuth2AuthorizedClientManager method authorize.

@Nullable
@Override
public OAuth2AuthorizedClient authorize(OAuth2AuthorizeRequest authorizeRequest) {
    Assert.notNull(authorizeRequest, "authorizeRequest cannot be null");
    String clientRegistrationId = authorizeRequest.getClientRegistrationId();
    OAuth2AuthorizedClient authorizedClient = authorizeRequest.getAuthorizedClient();
    Authentication principal = authorizeRequest.getPrincipal();
    HttpServletRequest servletRequest = getHttpServletRequestOrDefault(authorizeRequest.getAttributes());
    Assert.notNull(servletRequest, "servletRequest cannot be null");
    HttpServletResponse servletResponse = getHttpServletResponseOrDefault(authorizeRequest.getAttributes());
    Assert.notNull(servletResponse, "servletResponse cannot be null");
    OAuth2AuthorizationContext.Builder contextBuilder;
    if (authorizedClient != null) {
        contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
    } else {
        authorizedClient = this.authorizedClientRepository.loadAuthorizedClient(clientRegistrationId, principal, servletRequest);
        if (authorizedClient != null) {
            contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
        } else {
            ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
            Assert.notNull(clientRegistration, "Could not find ClientRegistration with id '" + clientRegistrationId + "'");
            contextBuilder = OAuth2AuthorizationContext.withClientRegistration(clientRegistration);
        }
    }
    // @formatter:off
    OAuth2AuthorizationContext authorizationContext = contextBuilder.principal(principal).attributes((attributes) -> {
        Map<String, Object> contextAttributes = this.contextAttributesMapper.apply(authorizeRequest);
        if (!CollectionUtils.isEmpty(contextAttributes)) {
            attributes.putAll(contextAttributes);
        }
    }).build();
    // @formatter:on
    try {
        authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
    } catch (OAuth2AuthorizationException ex) {
        this.authorizationFailureHandler.onAuthorizationFailure(ex, principal, createAttributes(servletRequest, servletResponse));
        throw ex;
    }
    if (authorizedClient != null) {
        this.authorizationSuccessHandler.onAuthorizationSuccess(authorizedClient, principal, createAttributes(servletRequest, servletResponse));
    } else {
        // `authorizationContext.authorizedClient`.
        if (authorizationContext.getAuthorizedClient() != null) {
            return authorizationContext.getAuthorizedClient();
        }
    }
    return authorizedClient;
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) OAuth2AuthorizationSuccessHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationSuccessHandler) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) HashMap(java.util.HashMap) AuthorizedClientServiceOAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager) Function(java.util.function.Function) RequestContextHolder(org.springframework.web.context.request.RequestContextHolder) Map(java.util.Map) OAuth2AuthorizedClientManager(org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager) RequestAttributes(org.springframework.web.context.request.RequestAttributes) Nullable(org.springframework.lang.Nullable) OAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.OAuth2AuthorizationFailureHandler) OAuth2AuthorizedClientProviderBuilder(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) RemoveAuthorizedClientOAuth2AuthorizationFailureHandler(org.springframework.security.oauth2.client.RemoveAuthorizedClientOAuth2AuthorizationFailureHandler) ServletRequestAttributes(org.springframework.web.context.request.ServletRequestAttributes) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) OAuth2AuthorizeRequest(org.springframework.security.oauth2.client.OAuth2AuthorizeRequest) OAuth2AuthorizedClientProvider(org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider) CollectionUtils(org.springframework.util.CollectionUtils) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Authentication(org.springframework.security.core.Authentication) Collections(java.util.Collections) ClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ClientRegistrationRepository) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) Authentication(org.springframework.security.core.Authentication) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) HashMap(java.util.HashMap) Map(java.util.Map) Nullable(org.springframework.lang.Nullable)

Example 19 with OAuth2AuthorizationException

use of org.springframework.security.oauth2.core.OAuth2AuthorizationException 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 20 with OAuth2AuthorizationException

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

the class ServerOAuth2AuthorizationCodeAuthenticationTokenConverter method authenticationRequest.

private Mono<OAuth2AuthorizationCodeAuthenticationToken> authenticationRequest(ServerWebExchange exchange, OAuth2AuthorizationRequest authorizationRequest) {
    // @formatter:off
    return Mono.just(authorizationRequest).map(OAuth2AuthorizationRequest::getAttributes).flatMap((attributes) -> {
        String id = (String) attributes.get(OAuth2ParameterNames.REGISTRATION_ID);
        if (id == null) {
            return oauth2AuthorizationException(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE);
        }
        return this.clientRegistrationRepository.findByRegistrationId(id);
    }).switchIfEmpty(oauth2AuthorizationException(CLIENT_REGISTRATION_NOT_FOUND_ERROR_CODE)).map((clientRegistration) -> {
        OAuth2AuthorizationResponse authorizationResponse = convertResponse(exchange);
        OAuth2AuthorizationCodeAuthenticationToken authenticationRequest = new OAuth2AuthorizationCodeAuthenticationToken(clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse));
        return authenticationRequest;
    });
// @formatter:on
}
Also used : OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)

Aggregations

OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)24 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)19 Test (org.junit.jupiter.api.Test)10 Authentication (org.springframework.security.core.Authentication)8 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)8 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)6 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)5 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)5 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)5 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)4 URI (java.net.URI)3 Instant (java.time.Instant)3 Collections (java.util.Collections)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 OAuth2AuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken)3 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)3 OAuth2ErrorCodes (org.springframework.security.oauth2.core.OAuth2ErrorCodes)3 OAuth2ParameterNames (org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames)3 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)3