Search in sources :

Example 26 with OAuth2AuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken in project spring-security by spring-projects.

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenDefaultOAuth2AuthorizedClientFalseThenEmpty.

@Test
public void filterWhenDefaultOAuth2AuthorizedClientFalseThenEmpty() {
    ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
    OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
    OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, user.getAuthorities(), "client-id");
    // @formatter:off
    this.function.filter(request, this.exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)).block();
    // @formatter:on
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(1);
    verifyZeroInteractions(this.clientRegistrationRepository, this.authorizedClientRepository);
}
Also used : DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 27 with OAuth2AuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken in project spring-security by spring-projects.

the class ServletOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenChainedThenDefaultsStillAvailable.

// gh-6483
@Test
public void filterWhenChainedThenDefaultsStillAvailable() throws Exception {
    this.function.setDefaultOAuth2AuthorizedClient(true);
    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    MockHttpServletResponse servletResponse = new MockHttpServletResponse();
    OAuth2User user = mock(OAuth2User.class);
    List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
    OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, authorities, this.registration.getRegistrationId());
    OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient(this.registration, "principalName", this.accessToken);
    given(this.authorizedClientRepository.loadAuthorizedClient(eq(authentication.getAuthorizedClientRegistrationId()), eq(authentication), eq(servletRequest))).willReturn(authorizedClient);
    // Default request attributes set
    final ClientRequest request1 = ClientRequest.create(HttpMethod.GET, URI.create("https://example1.com")).attributes((attrs) -> attrs.putAll(getDefaultRequestAttributes())).build();
    // Default request attributes NOT set
    final ClientRequest request2 = ClientRequest.create(HttpMethod.GET, URI.create("https://example2.com")).build();
    Context context = context(servletRequest, servletResponse, authentication);
    this.function.filter(request1, this.exchange).flatMap((response) -> this.function.filter(request2, this.exchange)).subscriberContext(context).block();
    List<ClientRequest> requests = this.exchange.getRequests();
    assertThat(requests).hasSize(2);
    ClientRequest request = requests.get(0);
    assertThat(request.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
    assertThat(request.url().toASCIIString()).isEqualTo("https://example1.com");
    assertThat(request.method()).isEqualTo(HttpMethod.GET);
    assertThat(getBody(request)).isEmpty();
    request = requests.get(1);
    assertThat(request.headers().getFirst(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer token-0");
    assertThat(request.url().toASCIIString()).isEqualTo("https://example2.com");
    assertThat(request.method()).isEqualTo(HttpMethod.GET);
    assertThat(getBody(request)).isEmpty();
}
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) Context(reactor.util.context.Context) OAuth2AuthorizationContext(org.springframework.security.oauth2.client.OAuth2AuthorizationContext) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Example 28 with OAuth2AuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken in project spring-security by spring-projects.

the class OAuth2AuthorizedClientArgumentResolverTests method resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves.

@Test
public void resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves() throws Exception {
    OAuth2AuthenticationToken authentication = mock(OAuth2AuthenticationToken.class);
    given(authentication.getAuthorizedClientRegistrationId()).willReturn("client1");
    SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
    securityContext.setAuthentication(authentication);
    SecurityContextHolder.setContext(securityContext);
    MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AuthorizedClient.class);
    assertThat(this.argumentResolver.resolveArgument(methodParameter, null, new ServletWebRequest(this.request, this.response), null)).isSameAs(this.authorizedClient1);
}
Also used : OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) SecurityContext(org.springframework.security.core.context.SecurityContext) MethodParameter(org.springframework.core.MethodParameter) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) Test(org.junit.jupiter.api.Test)

Example 29 with OAuth2AuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken in project spring-security by spring-projects.

the class OAuth2AuthorizedClientArgumentResolverTests method resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves.

@Test
public void resolveArgumentWhenRegistrationIdEmptyAndOAuth2AuthenticationThenResolves() {
    given(this.authorizedClientRepository.loadAuthorizedClient(anyString(), any(), any())).willReturn(Mono.just(this.authorizedClient));
    this.authentication = mock(OAuth2AuthenticationToken.class);
    given(((OAuth2AuthenticationToken) this.authentication).getAuthorizedClientRegistrationId()).willReturn("client1");
    MethodParameter methodParameter = this.getMethodParameter("registrationIdEmpty", OAuth2AuthorizedClient.class);
    resolveArgument(methodParameter);
}
Also used : OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) MethodParameter(org.springframework.core.MethodParameter) Test(org.junit.jupiter.api.Test)

Example 30 with OAuth2AuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken in project spring-security by spring-projects.

the class ServerOAuth2AuthorizedClientExchangeFilterFunctionTests method filterWhenClientRegistrationIdFromAuthenticationThenAuthorizedClientResolved.

@Test
public void filterWhenClientRegistrationIdFromAuthenticationThenAuthorizedClientResolved() {
    this.function.setDefaultOAuth2AuthorizedClient(true);
    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();
    OAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user");
    OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(user, user.getAuthorities(), "client-id");
    this.function.filter(request, this.exchange).subscriberContext(ReactiveSecurityContextHolder.withAuthentication(authentication)).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 : DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2RefreshToken(org.springframework.security.oauth2.core.OAuth2RefreshToken) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) ClientRequest(org.springframework.web.reactive.function.client.ClientRequest) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2AuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken)41 Test (org.junit.jupiter.api.Test)34 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)11 Collection (java.util.Collection)6 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)6 DefaultOidcUser (org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser)6 DefaultOAuth2User (org.springframework.security.oauth2.core.user.DefaultOAuth2User)6 RegisteredOAuth2AuthorizedClient (org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient)5 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)5 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)5 WebFilterExchange (org.springframework.security.web.server.WebFilterExchange)5 HttpHeaders (org.springframework.http.HttpHeaders)4 URI (java.net.URI)3 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)3 BeforeEach (org.junit.jupiter.api.BeforeEach)3 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)3 Mock (org.mockito.Mock)3 MockitoExtension (org.mockito.junit.jupiter.MockitoExtension)3 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 AuthorityUtils (org.springframework.security.core.authority.AuthorityUtils)3