Search in sources :

Example 11 with ClientRequest

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenAuthorizedClientNullThenAuthorizationHeaderNull.

@Test
public void filterWhenAuthorizedClientNullThenAuthorizationHeaderNull() {
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
    this.function.filter(request, this.exchange).block();
    assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
Also used : ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 12 with ClientRequest

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenNotExpiredThenShouldRefreshFalse.

@Test
public void filterWhenNotExpiredThenShouldRefreshFalse() {
    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();
    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();
}
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 13 with ClientRequest

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenClientCredentialsClientNotAuthorizedAndOutsideRequestContextThenGetNewToken.

// gh-7544
@Test
public void filterWhenClientCredentialsClientNotAuthorizedAndOutsideRequestContextThenGetNewToken() {
    setupMockHeaders();
    // Use UnAuthenticatedServerOAuth2AuthorizedClientRepository when operating
    // outside of a request context
    ServerOAuth2AuthorizedClientRepository unauthenticatedAuthorizedClientRepository = spy(new UnAuthenticatedServerOAuth2AuthorizedClientRepository());
    this.function = new ServerOAuth2AuthorizedClientExchangeFilterFunction(this.clientRegistrationRepository, unauthenticatedAuthorizedClientRepository);
    this.function.setClientCredentialsTokenResponseClient(this.clientCredentialsTokenResponseClient);
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
    given(this.clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
    given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))).willReturn(Mono.just(registration));
    // @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).block();
    verify(unauthenticatedAuthorizedClientRepository).loadAuthorizedClient(any(), any(), any());
    verify(this.clientCredentialsTokenResponseClient).getTokenResponse(any());
    verify(unauthenticatedAuthorizedClientRepository).saveAuthorizedClient(any(), any(), any());
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    ClientRequest request1 = requests.get(0);
    assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer new-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) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) UnAuthenticatedServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) UnAuthenticatedServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.UnAuthenticatedServerOAuth2AuthorizedClientRepository) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 14 with ClientRequest

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenUnauthorizedThenInvokeFailureHandler.

@Test
public void filterWhenUnauthorizedThenInvokeFailureHandler() {
    setupMockHeaders();
    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
    given(this.exchange.getResponse().rawStatusCode()).willReturn(HttpStatus.UNAUTHORIZED.value());
    this.function.filter(request, this.exchange).subscriberContext(serverWebExchange()).block();
    assertThat(publisherProbe.wasSubscribed()).isTrue();
    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("invalid_token");
        assertThat(ex).hasNoCause();
        assertThat(ex).hasMessageContaining("[invalid_token]");
    });
    assertThat(this.authenticationCaptor.getValue()).isInstanceOf(AnonymousAuthenticationToken.class);
    assertThat(this.attributesCaptor.getValue()).containsExactly(entry(ServerWebExchange.class.getName(), this.serverWebExchange));
}
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 15 with ClientRequest

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

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenPasswordClientNotAuthorizedThenGetNewToken.

@Test
public void filterWhenPasswordClientNotAuthorizedThenGetNewToken() {
    setupMocks();
    TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this");
    ClientRegistration registration = TestClientRegistrations.password().build();
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
    given(this.passwordTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    given(this.clientRegistrationRepository.findByRegistrationId(eq(registration.getRegistrationId()))).willReturn(Mono.just(registration));
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(registration.getRegistrationId()), eq(authentication), any())).willReturn(Mono.empty());
    // Set custom contextAttributesMapper capable of mapping the form parameters
    this.authorizedClientManager.setContextAttributesMapper((authorizeRequest) -> {
        ServerWebExchange serverWebExchange = authorizeRequest.getAttribute(ServerWebExchange.class.getName());
        return Mono.just(serverWebExchange).flatMap(ServerWebExchange::getFormData).map((formData) -> {
            Map<String, Object> contextAttributes = new HashMap<>();
            String username = formData.getFirst(OAuth2ParameterNames.USERNAME);
            String password = formData.getFirst(OAuth2ParameterNames.PASSWORD);
            if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
                contextAttributes.put(OAuth2AuthorizationContext.USERNAME_ATTRIBUTE_NAME, username);
                contextAttributes.put(OAuth2AuthorizationContext.PASSWORD_ATTRIBUTE_NAME, password);
            }
            return contextAttributes;
        });
    });
    this.serverWebExchange = MockServerWebExchange.builder(MockServerHttpRequest.post("/").contentType(MediaType.APPLICATION_FORM_URLENCODED).body("username=username&password=password")).build();
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServerOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(registration.getRegistrationId())).build();
    this.function.filter(request, this.exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)).subscriberContext(serverWebExchange()).block();
    verify(this.passwordTokenResponseClient).getTokenResponse(any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(authentication), any());
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    ClientRequest request1 = requests.get(0);
    assertThat(request1.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer new-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) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) ServerWebExchange(org.springframework.web.server.ServerWebExchange) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) HashMap(java.util.HashMap) 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