Search in sources :

Example 11 with OAuth2AuthorizationException

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

the class AuthorizedClientServiceOAuth2AuthorizedClientManager 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();
    OAuth2AuthorizationContext.Builder contextBuilder;
    if (authorizedClient != null) {
        contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
    } else {
        ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(clientRegistrationId);
        Assert.notNull(clientRegistration, "Could not find ClientRegistration with id '" + clientRegistrationId + "'");
        authorizedClient = this.authorizedClientService.loadAuthorizedClient(clientRegistrationId, principal.getName());
        if (authorizedClient != null) {
            contextBuilder = OAuth2AuthorizationContext.withAuthorizedClient(authorizedClient);
        } else {
            contextBuilder = OAuth2AuthorizationContext.withClientRegistration(clientRegistration);
        }
    }
    OAuth2AuthorizationContext authorizationContext = buildAuthorizationContext(authorizeRequest, principal, contextBuilder);
    try {
        authorizedClient = this.authorizedClientProvider.authorize(authorizationContext);
    } catch (OAuth2AuthorizationException ex) {
        this.authorizationFailureHandler.onAuthorizationFailure(ex, principal, Collections.emptyMap());
        throw ex;
    }
    if (authorizedClient != null) {
        this.authorizationSuccessHandler.onAuthorizationSuccess(authorizedClient, principal, Collections.emptyMap());
    } else {
        // `authorizationContext.authorizedClient`.
        if (authorizationContext.getAuthorizedClient() != null) {
            return authorizationContext.getAuthorizedClient();
        }
    }
    return authorizedClient;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Authentication(org.springframework.security.core.Authentication) Nullable(org.springframework.lang.Nullable)

Example 12 with OAuth2AuthorizationException

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

the class OAuth2AuthorizationCodeGrantFilterTests method doFilterWhenAuthorizationFailsThenHandleOAuth2AuthorizationException.

@Test
public void doFilterWhenAuthorizationFailsThenHandleOAuth2AuthorizationException() throws Exception {
    MockHttpServletRequest authorizationRequest = createAuthorizationRequest("/callback/client-1");
    MockHttpServletRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
    MockHttpServletResponse response = new MockHttpServletResponse();
    FilterChain filterChain = mock(FilterChain.class);
    this.setUpAuthorizationRequest(authorizationRequest, response, this.registration1);
    OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_GRANT);
    given(this.authenticationManager.authenticate(any(Authentication.class))).willThrow(new OAuth2AuthorizationException(error));
    this.filter.doFilter(authorizationResponse, response, filterChain);
    assertThat(response.getRedirectedUrl()).isEqualTo("http://localhost/callback/client-1?error=invalid_grant");
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Authentication(org.springframework.security.core.Authentication) FilterChain(jakarta.servlet.FilterChain) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 13 with OAuth2AuthorizationException

use of org.springframework.security.oauth2.core.OAuth2AuthorizationException in project jhipster-registry by jhipster.

the class AuthorizationHeaderUtil method refreshTokenClient.

private OAuth2AccessTokenResponse refreshTokenClient(OAuth2AuthorizedClient currentClient) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.REFRESH_TOKEN.getValue());
    formParameters.add(OAuth2ParameterNames.REFRESH_TOKEN, currentClient.getRefreshToken().getTokenValue());
    formParameters.add(OAuth2ParameterNames.CLIENT_ID, currentClient.getClientRegistration().getClientId());
    RequestEntity requestEntity = RequestEntity.post(URI.create(currentClient.getClientRegistration().getProviderDetails().getTokenUri())).contentType(MediaType.APPLICATION_FORM_URLENCODED).body(formParameters);
    try {
        RestTemplate r = restTemplate(currentClient.getClientRegistration().getClientId(), currentClient.getClientRegistration().getClientSecret());
        ResponseEntity<OAuthIdpTokenResponseDTO> responseEntity = r.exchange(requestEntity, OAuthIdpTokenResponseDTO.class);
        return toOAuth2AccessTokenResponse(responseEntity.getBody());
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to refresh token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) RequestEntity(org.springframework.http.RequestEntity) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 14 with OAuth2AuthorizationException

use of org.springframework.security.oauth2.core.OAuth2AuthorizationException in project jhipster-registry by jhipster.

the class UaaAuthorizationHeaderUtil method retrieveNewAccessToken.

private OAuth2AccessToken retrieveNewAccessToken(ClientRegistration clientRegistration) {
    MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
    formParameters.add(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.CLIENT_CREDENTIALS.getValue());
    RequestEntity requestEntity = RequestEntity.post(URI.create(clientRegistration.getProviderDetails().getTokenUri())).contentType(MediaType.APPLICATION_FORM_URLENCODED).body(formParameters);
    try {
        ResponseEntity<OAuth2AccessTokenResponse> responseEntity = this.uaaRestTemplate.exchange(requestEntity, OAuth2AccessTokenResponse.class);
        return Objects.requireNonNull(responseEntity.getBody()).getAccessToken();
    } catch (OAuth2AuthorizationException e) {
        log.error("Unable to get access token", e);
        throw new OAuth2AuthenticationException(e.getError(), e);
    }
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RequestEntity(org.springframework.http.RequestEntity) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException)

Example 15 with OAuth2AuthorizationException

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

the class OAuth2AuthorizationCodeReactiveAuthenticationManagerTests method authenticateWhenOAuth2AuthorizationExceptionThenOAuth2AuthorizationException.

@Test
public void authenticateWhenOAuth2AuthorizationExceptionThenOAuth2AuthorizationException() {
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.error(() -> new OAuth2AuthorizationException(new OAuth2Error("error"))));
    assertThatExceptionOfType(OAuth2AuthorizationException.class).isThrownBy(() -> authenticate());
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Test(org.junit.jupiter.api.Test)

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