use of org.springframework.web.reactive.function.client.ClientRequest in project spring-security by spring-projects.
the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenRefreshRequiredThenRefreshAndResponseDoesNotContainRefreshToken.
@Test
public void filterWhenRefreshRequiredThenRefreshAndResponseDoesNotContainRefreshToken() {
OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).build();
RestOperations refreshTokenClient = mock(RestOperations.class);
given(refreshTokenClient.exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class))).willReturn(new ResponseEntity(response, HttpStatus.OK));
DefaultRefreshTokenTokenResponseClient refreshTokenTokenResponseClient = new DefaultRefreshTokenTokenResponseClient();
refreshTokenTokenResponseClient.setRestOperations(refreshTokenClient);
RefreshTokenOAuth2AuthorizedClientProvider authorizedClientProvider = new RefreshTokenOAuth2AuthorizedClientProvider();
authorizedClientProvider.setAccessTokenResponseClient(refreshTokenTokenResponseClient);
DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(this.clientRegistrationRepository, this.authorizedClientRepository);
authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);
this.function = new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
this.accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(), issuedAt, accessTokenExpiresAt);
OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", issuedAt);
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(new MockHttpServletRequest())).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(new MockHttpServletResponse())).build();
this.function.filter(request, this.exchange).block();
verify(refreshTokenClient).exchange(any(RequestEntity.class), eq(OAuth2AccessTokenResponse.class));
verify(this.authorizedClientRepository).saveAuthorizedClient(this.authorizedClientCaptor.capture(), eq(this.authentication), any(), any());
OAuth2AuthorizedClient newAuthorizedClient = this.authorizedClientCaptor.getValue();
assertThat(newAuthorizedClient.getAccessToken()).isEqualTo(response.getAccessToken());
assertThat(newAuthorizedClient.getRefreshToken().getTokenValue()).isEqualTo(refreshToken.getTokenValue());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-1");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
use of org.springframework.web.reactive.function.client.ClientRequest in project spring-security by spring-projects.
the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenWWWAuthenticateHeaderIncludesErrorThenInvokeFailureHandler.
@Test
public void filterWhenWWWAuthenticateHeaderIncludesErrorThenInvokeFailureHandler() {
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();
String wwwAuthenticateHeader = "Bearer error=\"insufficient_scope\", " + "error_description=\"The request requires higher privileges than provided by the access token.\", " + "error_uri=\"https://tools.ietf.org/html/rfc6750#section-3.1\"";
ClientResponse.Headers headers = mock(ClientResponse.Headers.class);
given(headers.header(eq(HttpHeaders.WWW_AUTHENTICATE))).willReturn(Collections.singletonList(wwwAuthenticateHeader));
given(this.exchange.getResponse().headers()).willReturn(headers);
this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
this.function.filter(request, this.exchange).block();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture());
assertThat(this.authorizationExceptionCaptor.getValue()).isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
assertThat(ex.getError().getDescription()).isEqualTo("The request requires higher privileges than provided by the access token.");
assertThat(ex.getError().getUri()).isEqualTo("https://tools.ietf.org/html/rfc6750#section-3.1");
assertThat(ex).hasNoCause();
assertThat(ex).hasMessageContaining(OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
});
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.web.reactive.function.client.ClientRequest in project spring-security by spring-projects.
the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenClientCredentialsTokenNotExpiredThenUseCurrentToken.
@Test
public void filterWhenClientCredentialsTokenNotExpiredThenUseCurrentToken() {
this.registration = TestClientRegistrations.clientCredentials().build();
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, null);
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(this.authentication)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(new MockHttpServletRequest())).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(new MockHttpServletResponse())).build();
this.function.filter(request, this.exchange).block();
verify(this.authorizedClientRepository, never()).saveAuthorizedClient(any(), eq(this.authentication), any(), any());
verify(this.clientCredentialsTokenResponseClient, never()).getTokenResponse(any());
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request1 = requests.get(0);
assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request1.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request1)).isEmpty();
}
use of org.springframework.web.reactive.function.client.ClientRequest in project spring-security by spring-projects.
the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenUnauthorizedWithWebClientExceptionThenInvokeFailureHandler.
@Test
public void filterWhenUnauthorizedWithWebClientExceptionThenInvokeFailureHandler() {
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);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).build();
// @formatter:on
WebClientResponseException exception = WebClientResponseException.create(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8);
ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
// @formatter:off
assertThatExceptionOfType(WebClientResponseException.class).isThrownBy(() -> this.function.filter(request, throwingExchangeFunction).subscriberContext(serverWebExchange()).block()).isEqualTo(exception);
// @formatter:on
assertThat(publisherProbe.wasSubscribed()).isTrue();
verify(this.authorizationFailureHandler).onAuthorizationFailure(this.authorizationExceptionCaptor.capture(), this.authenticationCaptor.capture(), this.attributesCaptor.capture());
// @formatter:off
assertThat(this.authorizationExceptionCaptor.getValue()).isInstanceOfSatisfying(ClientAuthorizationException.class, (ex) -> {
assertThat(ex.getClientRegistrationId()).isEqualTo(this.registration.getRegistrationId());
assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token");
assertThat(ex).hasCause(exception);
assertThat(ex).hasMessageContaining("[invalid_token]");
});
// @formatter:on
assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
assertThat(this.attributesCaptor.getValue()).containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
use of org.springframework.web.reactive.function.client.ClientRequest in project spring-security by spring-projects.
the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenRefreshTokenNullThenShouldRefreshFalse.
@Test
public void filterWhenRefreshTokenNullThenShouldRefreshFalse() {
OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken);
// @formatter:off
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).build();
this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block();
// @formatter:on
List<ClientRequest> requests = this.exchange.getRequests();
assertThat(requests).hasSize(1);
ClientRequest request0 = requests.get(0);
assertThat(request0.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
assertThat(request0.url().toASCIIString()).isEqualTo("https://example.com");
assertThat(request0.method()).isEqualTo(HttpMethod.GET);
assertThat(getBody(request0)).isEmpty();
}
Aggregations