Search in sources :

Example 11 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse 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 12 with OAuth2AccessTokenResponse

use of org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse 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)

Example 13 with OAuth2AccessTokenResponse

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenJwtBearerClientNotAuthorizedThenExchangeToken.

@Test
public void filterWhenJwtBearerClientNotAuthorizedThenExchangeToken() {
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("exchanged-token").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
    given(this.jwtBearerTokenResponseClient.getTokenResponse(any())).willReturn(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(registration);
    Jwt jwtAssertion = TestJwts.jwt().build();
    Authentication jwtAuthentication = new TestingAuthenticationToken(jwtAssertion, jwtAssertion);
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId(registration.getRegistrationId())).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.authentication(jwtAuthentication)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletRequest(servletRequest)).attributes(ServletOAuth2AuthorizedClientExchangeFilterFunction.httpServletResponse(servletResponse)).build();
    this.function.filter(request, this.exchange).block();
    verify(this.jwtBearerTokenResponseClient).getTokenResponse(any());
    verify(this.authorizedClientRepository).saveAuthorizedClient(any(), eq(jwtAuthentication), 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 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) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 14 with OAuth2AccessTokenResponse

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenClientCredentialsTokenExpiredThenGetNewToken.

@Test
public void filterWhenClientCredentialsTokenExpiredThenGetNewToken() {
    this.registration = TestClientRegistrations.clientCredentials().build();
    OAuth2AccessTokenResponse accessTokenResponse = TestOAuth2AccessTokenResponses.accessTokenResponse().build();
    given(this.clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    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);
    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).saveAuthorizedClient(any(), eq(this.authentication), any(), any());
    verify(this.clientCredentialsTokenResponseClient).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");
    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) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Instant(java.time.Instant) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Example 15 with OAuth2AccessTokenResponse

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

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenRefreshRequiredThenRefresh.

@Test
public void filterWhenRefreshRequiredThenRefresh() {
    OAuth2AccessTokenResponse response = OAuth2AccessTokenResponse.withToken("token-1").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(3600).refreshToken("refresh-1").build();
    given(this.refreshTokenTokenResponseClient.getTokenResponse(any())).willReturn(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);
    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.refreshTokenTokenResponseClient).getTokenResponse(any());
    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()).isEqualTo(response.getRefreshToken());
    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) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Instant(java.time.Instant) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)134 Test (org.junit.jupiter.api.Test)122 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)43 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)40 Instant (java.time.Instant)37 HashMap (java.util.HashMap)32 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)27 Mono (reactor.core.publisher.Mono)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)16 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)16 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)15 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)15 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)14 BeforeEach (org.junit.jupiter.api.BeforeEach)13 Map (java.util.Map)12 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)11 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11