Search in sources :

Example 51 with ClientRequest

use of org.springframework.web.reactive.function.client.ClientRequest in project spring-security by spring-projects.

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method assertHttpStatusWithWebClientExceptionInvokesFailureHandler.

private void assertHttpStatusWithWebClientExceptionInvokesFailureHandler(HttpStatus httpStatus, String expectedErrorCode) {
    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();
    WebClientResponseException exception = WebClientResponseException.create(httpStatus.value(), httpStatus.getReasonPhrase(), HttpHeaders.EMPTY, new byte[0], StandardCharsets.UTF_8);
    ExchangeFunction throwingExchangeFunction = (r) -> Mono.error(exception);
    this.function.setAuthorizationFailureHandler(this.authorizationFailureHandler);
    assertThatExceptionOfType(WebClientResponseException.class).isThrownBy(() -> this.function.filter(request, throwingExchangeFunction).block()).isEqualTo(exception);
    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(expectedErrorCode);
        assertThat(ex).hasCause(exception);
        assertThat(ex).hasMessageContaining(expectedErrorCode);
    });
    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 : 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) WebClientResponseException(org.springframework.web.reactive.function.client.WebClientResponseException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) 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)

Example 52 with ClientRequest

use of org.springframework.web.reactive.function.client.ClientRequest in project spring-security by spring-projects.

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenAuthorizedClientThenAuthorizationHeader.

@Test
public void filterWhenAuthorizedClientThenAuthorizationHeader() {
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken);
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.oauth2AuthorizedClient(authorizedClient)).build();
    // @formatter:off
    this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block();
    // @formatter:on
    assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
Also used : OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 53 with ClientRequest

use of org.springframework.web.reactive.function.client.ClientRequest in project spring-security by spring-projects.

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenRefreshRequiredAndEmptyReactiveSecurityContextThenSaved.

@Test
public void filterWhenRefreshRequiredAndEmptyReactiveSecurityContextThenSaved() {
    setupMocks();
    OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build();
    given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(response));
    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);
    // @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
    verify(this.refreshTokenTokenResponseClient).getTokenResponse(any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(any(), any(), any());
    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();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 54 with ClientRequest

use of org.springframework.web.reactive.function.client.ClientRequest in project spring-security by spring-projects.

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenDefaultClientRegistrationIdThenAuthorizedClientResolved.

@Test
public void filterWhenDefaultClientRegistrationIdThenAuthorizedClientResolved() {
    this.function.setDefaultClientRegistrationId(this.registration.getRegistrationId());
    OAuth2RefreshToken refreshToken = new OAuth2RefreshToken("refresh-token", this.accessToken.getIssuedAt());
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken, refreshToken);
    given(this.authorizedClientRepository.loadAuthorizedClient(any(), any(), any())).willReturn(Mono.just(authorizedClient));
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
    this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block();
    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();
}
Also used : OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 55 with ClientRequest

use of org.springframework.web.reactive.function.client.ClientRequest in project spring-security by spring-projects.

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenJwtBearerClientNotAuthorizedThenExchangeToken.

@Test
public void filterWhenJwtBearerClientNotAuthorizedThenExchangeToken() {
    setupMocks();
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("exchanged-token").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
    given(this.jwtBearerTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    // @formatter:off
    ClientRegistration registration = ClientRegistration.withRegistrationId("jwt-bearer").clientId("client-id").clientSecret("client-secret").clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC).authorizationGrantType(AuthorizationGrantType.JWT_BEARER).scope("read", "write").tokenUri("https://example.com/oauth/token").build();
    // @formatter:on
    given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))).willReturn(Mono.just(registration));
    Jwt jwtAssertion = TestJwts.jwt().build();
    Authentication jwtAuthentication = new TestingAuthenticationToken(jwtAssertion, jwtAssertion);
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(registration.getRegistrationId()), eq(jwtAuthentication), any())).willReturn(Mono.empty());
    // @formatter:off
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(registration.getRegistrationId())).build();
    // @formatter:on
    this.function.filter(request, this.exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(jwtAuthentication)).subscriberContext(serverWebExchange()).block();
    verify(this.jwtBearerTokenResponseClient).getTokenResponse(any());
    verify(this.authorizedClientRepository).loadAuthorizedClient(eq(registration.getRegistrationId()), eq(jwtAuthentication), any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(jwtAuthentication), any());
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    ClientRequest request1 = requests.get(0);
    assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer exchanged-token");
    assertThat(request1.url().toASCIIString()).isEqualTo("https://example.com");
    assertThat(request1.method()).isEqualTo(HttpMethod.GET);
    assertThat(getBody(request1)).isEmpty();
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Jwt(org.springframework.security.oauth2.jwt.Jwt) Authentication(org.springframework.security.core.Authentication) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Aggregations

ClientRequest (org.springframework.web.reactive.function.client.ClientRequest)63 Test (org.junit.jupiter.api.Test)59 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)34 OAuth2RefreshToken (org.springframework.security.oauth2.core.OAuth2RefreshToken)21 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)18 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)18 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)18 ClientResponse (org.springframework.web.reactive.function.client.ClientResponse)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)15 Mono (reactor.core.publisher.Mono)14 Instant (java.time.Instant)13 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)13 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)13 ExchangeFunction (org.springframework.web.reactive.function.client.ExchangeFunction)13 URI (java.net.URI)12 HttpHeaders (org.springframework.http.HttpHeaders)12 HttpMethod (org.springframework.http.HttpMethod)12 HttpStatus (org.springframework.http.HttpStatus)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)11 Duration (java.time.Duration)10