Search in sources :

Example 21 with ClientRegistration

use of org.springframework.security.oauth2.client.registration.ClientRegistration in project spring-security by spring-projects.

the class OAuth2LoginAuthenticationFilterTests method setUpAuthenticationResult.

private void setUpAuthenticationResult(ClientRegistration registration) {
    OAuth2User user = mock(OAuth2User.class);
    given(user.getName()).willReturn(this.principalName1);
    this.loginAuthentication = mock(OAuth2LoginAuthenticationToken.class);
    given(this.loginAuthentication.getPrincipal()).willReturn(user);
    given(this.loginAuthentication.getName()).willReturn(this.principalName1);
    given(this.loginAuthentication.getAuthorities()).willReturn(AuthorityUtils.createAuthorityList("ROLE_USER"));
    given(this.loginAuthentication.getClientRegistration()).willReturn(registration);
    given(this.loginAuthentication.getAuthorizationExchange()).willReturn(TestOAuth2AuthorizationExchanges.success());
    given(this.loginAuthentication.getAccessToken()).willReturn(mock(OAuth2AccessToken.class));
    given(this.loginAuthentication.getRefreshToken()).willReturn(mock(OAuth2RefreshToken.class));
    given(this.loginAuthentication.isAuthenticated()).willReturn(true);
    given(this.authenticationManager.authenticate(any(Authentication.class))).willReturn(this.loginAuthentication);
}
Also used : OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Authentication(org.springframework.security.core.Authentication) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)

Example 22 with ClientRegistration

use of org.springframework.security.oauth2.client.registration.ClientRegistration in project spring-security by spring-projects.

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenClientCredentialsTokenExpiredThenGetNewToken.

@Test
public void filterWhenClientCredentialsTokenExpiredThenGetNewToken() {
    setupMocks();
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("new-token").tokenType(OAuth2AccessToken.TokenType.BEARER).expiresIn(360).build();
    // @formatter:on
    given(this.clientCredentialsTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
    Instant issuedAt = Instant.now().minus(Duration.ofDays(1));
    Instant accessTokenExpiresAt = issuedAt.plus(Duration.ofHours(1));
    OAuth2AccessToken accessToken = new OAuth2AccessToken(this.accessToken.getTokenType(), this.accessToken.getTokenValue(), issuedAt, accessTokenExpiresAt);
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(registration, "principalName", accessToken, null);
    TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this");
    // @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(ReactiveSecurityContextHolder.withAuthentication(authentication)).subscriberContext(serverWebExchange()).block();
    // @formatter:on
    verify(this.clientCredentialsTokenResponseClient).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) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Instant(java.time.Instant) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 23 with ClientRegistration

use of org.springframework.security.oauth2.client.registration.ClientRegistration in project spring-security by spring-projects.

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenClientCredentialsTokenNotExpiredThenUseCurrentToken.

@Test
public void filterWhenClientCredentialsTokenNotExpiredThenUseCurrentToken() {
    TestingAuthenticationToken authentication = new TestingAuthenticationToken("test", "this");
    ClientRegistration registration = TestClientRegistrations.clientCredentials().build();
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(registration, "principalName", this.accessToken, null);
    // @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(ReactiveSecurityContextHolder.withAuthentication(authentication)).subscriberContext(serverWebExchange()).block();
    // @formatter:on
    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();
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 24 with ClientRegistration

use of org.springframework.security.oauth2.client.registration.ClientRegistration 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 25 with ClientRegistration

use of org.springframework.security.oauth2.client.registration.ClientRegistration 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

ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)258 Test (org.junit.jupiter.api.Test)214 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)55 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)52 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)44 HttpHeaders (org.springframework.http.HttpHeaders)42 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)36 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)32 Instant (java.time.Instant)28 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)27 BeforeEach (org.junit.jupiter.api.BeforeEach)27 TestClientRegistrations (org.springframework.security.oauth2.client.registration.TestClientRegistrations)27 MockResponse (okhttp3.mockwebserver.MockResponse)26 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)26 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)26 MultiValueMap (org.springframework.util.MultiValueMap)26 HashMap (java.util.HashMap)25 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)25 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)25 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)24