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));
}
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));
}
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;
}
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);
}
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
}
Aggregations