Search in sources :

Example 6 with OAuth2Error

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

the class OidcAuthorizationCodeReactiveAuthenticationManager method validateNonce.

private static Mono<OidcIdToken> validateNonce(OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication, OidcIdToken idToken) {
    String requestNonce = authorizationCodeAuthentication.getAuthorizationExchange().getAuthorizationRequest().getAttribute(OidcParameterNames.NONCE);
    if (requestNonce != null) {
        String nonceHash = getNonceHash(requestNonce);
        String nonceHashClaim = idToken.getNonce();
        if (nonceHashClaim == null || !nonceHashClaim.equals(nonceHash)) {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_NONCE_ERROR_CODE);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
    }
    return Mono.just(idToken);
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 7 with OAuth2Error

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

the class NimbusAuthorizationCodeTokenResponseClient method getTokenResponse.

private com.nimbusds.oauth2.sdk.TokenResponse getTokenResponse(AuthorizationGrant authorizationCodeGrant, URI tokenUri, ClientAuthentication clientAuthentication) {
    try {
        // Send the Access Token request
        TokenRequest tokenRequest = new TokenRequest(tokenUri, clientAuthentication, authorizationCodeGrant);
        HTTPRequest httpRequest = tokenRequest.toHTTPRequest();
        httpRequest.setAccept(MediaType.APPLICATION_JSON_VALUE);
        httpRequest.setConnectTimeout(30000);
        httpRequest.setReadTimeout(30000);
        return com.nimbusds.oauth2.sdk.TokenResponse.parse(httpRequest.send());
    } catch (ParseException | IOException ex) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE, "An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: " + ex.getMessage(), null);
        throw new OAuth2AuthorizationException(oauth2Error, ex);
    }
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) ParseException(com.nimbusds.oauth2.sdk.ParseException) IOException(java.io.IOException)

Example 8 with OAuth2Error

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

the class OAuth2AuthorizationCodeGrantWebFilterTests method filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException.

// gh-8609
@Test
public void filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() {
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
    given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
    MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
    OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
    given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
    given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new OAuth2AuthorizationException(new OAuth2Error("authorization_error"))));
    MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
    MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
    DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
    assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.filter.filter(exchange, chain).block()).satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode").isEqualTo("authorization_error"));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) DefaultWebFilterChain(org.springframework.web.server.handler.DefaultWebFilterChain) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 9 with OAuth2Error

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

the class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests method authorizeWhenOAuth2AuthorizationExceptionAndCustomFailureHandlerThenInvokeCustomFailureHandler.

@Test
public void authorizeWhenOAuth2AuthorizationExceptionAndCustomFailureHandlerThenInvokeCustomFailureHandler() {
    given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))).willReturn(Mono.just(this.clientRegistration));
    given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
    // @formatter:off
    OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal).build();
    // @formatter:on
    OAuth2AuthorizationException exception = new OAuth2AuthorizationException(new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT, null, null));
    given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(Mono.error(exception));
    PublisherProbe<Void> authorizationFailureHandlerProbe = PublisherProbe.empty();
    this.authorizedClientManager.setAuthorizationFailureHandler((client, principal, attributes) -> authorizationFailureHandlerProbe.mono());
    assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
    verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
    verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
    OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
    assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
    assertThat(authorizationContext.getAuthorizedClient()).isNull();
    assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
    authorizationFailureHandlerProbe.assertWasSubscribed();
    verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any());
    verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Test(org.junit.jupiter.api.Test)

Example 10 with OAuth2Error

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

the class AuthorizedClientServiceReactiveOAuth2AuthorizedClientManagerTests method authorizeWhenServerErrorThenDoNotRemoveAuthorizedClient.

@Test
public void authorizeWhenServerErrorThenDoNotRemoveAuthorizedClient() {
    given(this.clientRegistrationRepository.findByRegistrationId(eq(this.clientRegistration.getRegistrationId()))).willReturn(Mono.just(this.clientRegistration));
    given(this.authorizedClientService.loadAuthorizedClient(any(), any())).willReturn(Mono.empty());
    // @formatter:off
    OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId(this.clientRegistration.getRegistrationId()).principal(this.principal).build();
    // @formatter:on
    ClientAuthorizationException exception = new ClientAuthorizationException(new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, null, null), this.clientRegistration.getRegistrationId());
    given(this.authorizedClientProvider.authorize(any(OAuth2AuthorizationContext.class))).willReturn(Mono.error(exception));
    assertThatExceptionOfType(ClientAuthorizationException.class).isThrownBy(() -> this.authorizedClientManager.authorize(authorizeRequest).block()).isEqualTo(exception);
    verify(this.authorizedClientProvider).authorize(this.authorizationContextCaptor.capture());
    verify(this.contextAttributesMapper).apply(eq(authorizeRequest));
    OAuth2AuthorizationContext authorizationContext = this.authorizationContextCaptor.getValue();
    assertThat(authorizationContext.getClientRegistration()).isEqualTo(this.clientRegistration);
    assertThat(authorizationContext.getAuthorizedClient()).isNull();
    assertThat(authorizationContext.getPrincipal()).isEqualTo(this.principal);
    verify(this.authorizedClientService, never()).removeAuthorizedClient(any(), any());
    verify(this.authorizedClientService, never()).saveAuthorizedClient(any(), any());
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)125 Test (org.junit.jupiter.api.Test)53 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)50 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)24 Authentication (org.springframework.security.core.Authentication)22 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)17 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)16 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)16 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)15 Jwt (org.springframework.security.oauth2.jwt.Jwt)15 Instant (java.time.Instant)13 Map (java.util.Map)12 FilterChain (javax.servlet.FilterChain)12 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)11 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)10 OAuth2TokenValidatorResult (org.springframework.security.oauth2.core.OAuth2TokenValidatorResult)10 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)9 OAuth2AuthorizationContext (org.springframework.security.oauth2.client.OAuth2AuthorizationContext)9 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)8 BDDMockito.given (org.mockito.BDDMockito.given)8