Search in sources :

Example 56 with Context

use of reactor.util.context.Context 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 57 with Context

use of reactor.util.context.Context in project spring-security by spring-projects.

the class ReactorContextWebFilterTests method filterWhenPrincipalAndGetPrincipalThenInteractAndUseOriginalPrincipal.

@Test
public void filterWhenPrincipalAndGetPrincipalThenInteractAndUseOriginalPrincipal() {
    SecurityContextImpl context = new SecurityContextImpl(this.principal);
    given(this.repository.load(any())).willReturn(Mono.just(context));
    this.handler = WebTestHandler.bindToWebFilters(this.filter, (e, c) -> ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication).doOnSuccess((p) -> assertThat(p).isSameAs(this.principal)).flatMap((p) -> c.filter(e)));
    WebTestHandler.WebHandlerResult result = this.handler.exchange(this.exchange);
    this.securityContext.assertWasNotSubscribed();
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) TestPublisher(reactor.test.publisher.TestPublisher) WebTestHandler(org.springframework.security.test.web.reactive.server.WebTestHandler) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) StepVerifier(reactor.test.StepVerifier) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) Mock(org.mockito.Mock) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) Context(reactor.util.context.Context) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Mono(reactor.core.publisher.Mono) Test(org.junit.jupiter.api.Test) List(java.util.List) ReactiveSecurityContextHolder(org.springframework.security.core.context.ReactiveSecurityContextHolder) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) SecurityContext(org.springframework.security.core.context.SecurityContext) WebFilter(org.springframework.web.server.WebFilter) BDDMockito.given(org.mockito.BDDMockito.given) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) DefaultWebFilterChain(org.springframework.web.server.handler.DefaultWebFilterChain) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) Authentication(org.springframework.security.core.Authentication) WebFilterChain(org.springframework.web.server.WebFilterChain) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) WebTestHandler(org.springframework.security.test.web.reactive.server.WebTestHandler) SecurityContext(org.springframework.security.core.context.SecurityContext) Test(org.junit.jupiter.api.Test)

Example 58 with Context

use of reactor.util.context.Context in project spring-security by spring-projects.

the class CurrentSecurityContextArgumentResolverTests method resolveArgumentWithStringDepthProp.

@Test
public void resolveArgumentWithStringDepthProp() {
    MethodParameter parameter = ResolvableMethod.on(getClass()).named("securityContextWithDepthStringProp").build().arg(Mono.class, String.class);
    Authentication auth = buildAuthenticationWithPrincipal("auth_string");
    Context context = ReactiveSecurityContextHolder.withAuthentication(auth);
    Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange);
    Mono<String> obj = (Mono<String>) argument.subscriberContext(context).block();
    assertThat(obj.block()).isEqualTo("auth_string");
    ReactiveSecurityContextHolder.clearContext();
}
Also used : BindingContext(org.springframework.web.reactive.BindingContext) CurrentSecurityContext(org.springframework.security.core.annotation.CurrentSecurityContext) Context(reactor.util.context.Context) SecurityContext(org.springframework.security.core.context.SecurityContext) Authentication(org.springframework.security.core.Authentication) Mono(reactor.core.publisher.Mono) MethodParameter(org.springframework.core.MethodParameter) Test(org.junit.jupiter.api.Test)

Example 59 with Context

use of reactor.util.context.Context in project spring-security by spring-projects.

the class CurrentSecurityContextArgumentResolverTests method resolveArgumentErrorOnInvalidTypeWhenExplicitFalse.

@Test
public void resolveArgumentErrorOnInvalidTypeWhenExplicitFalse() {
    MethodParameter parameter = ResolvableMethod.on(getClass()).named("errorOnInvalidTypeWhenExplicitFalse").build().arg(Mono.class, String.class);
    Authentication auth = buildAuthenticationWithPrincipal("error_on_invalid_type_explicit_false");
    Context context = ReactiveSecurityContextHolder.withAuthentication(auth);
    Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange);
    Mono<String> obj = (Mono<String>) argument.subscriberContext(context).block();
    assertThat(obj.block()).isNull();
    ReactiveSecurityContextHolder.clearContext();
}
Also used : BindingContext(org.springframework.web.reactive.BindingContext) CurrentSecurityContext(org.springframework.security.core.annotation.CurrentSecurityContext) Context(reactor.util.context.Context) SecurityContext(org.springframework.security.core.context.SecurityContext) Authentication(org.springframework.security.core.Authentication) Mono(reactor.core.publisher.Mono) MethodParameter(org.springframework.core.MethodParameter) Test(org.junit.jupiter.api.Test)

Example 60 with Context

use of reactor.util.context.Context in project spring-security by spring-projects.

the class CurrentSecurityContextArgumentResolverTests method metaAnnotationWhenCurrentSecurityWithErrorOnInvalidTypeThenMisMatch.

@Test
public void metaAnnotationWhenCurrentSecurityWithErrorOnInvalidTypeThenMisMatch() {
    MethodParameter parameter = ResolvableMethod.on(getClass()).named("currentSecurityWithErrorOnInvalidTypeMisMatch").build().arg(Mono.class, String.class);
    Authentication auth = buildAuthenticationWithPrincipal("current_security_with_error_on_invalid_type_mismatch");
    Context context = ReactiveSecurityContextHolder.withAuthentication(auth);
    Mono<Object> argument = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange);
    assertThatExceptionOfType(ClassCastException.class).isThrownBy(() -> argument.subscriberContext(context).cast(Mono.class).block().block());
    ReactiveSecurityContextHolder.clearContext();
}
Also used : BindingContext(org.springframework.web.reactive.BindingContext) CurrentSecurityContext(org.springframework.security.core.annotation.CurrentSecurityContext) Context(reactor.util.context.Context) SecurityContext(org.springframework.security.core.context.SecurityContext) Authentication(org.springframework.security.core.Authentication) Mono(reactor.core.publisher.Mono) MethodParameter(org.springframework.core.MethodParameter) Test(org.junit.jupiter.api.Test)

Aggregations

Context (reactor.util.context.Context)66 Test (org.junit.jupiter.api.Test)29 Test (org.junit.Test)28 Mono (reactor.core.publisher.Mono)25 Authentication (org.springframework.security.core.Authentication)23 SecurityContext (org.springframework.security.core.context.SecurityContext)23 MethodParameter (org.springframework.core.MethodParameter)17 CurrentSecurityContext (org.springframework.security.core.annotation.CurrentSecurityContext)17 BindingContext (org.springframework.web.reactive.BindingContext)17 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)16 AtomicReference (java.util.concurrent.atomic.AtomicReference)14 ArrayList (java.util.ArrayList)13 Consumer (java.util.function.Consumer)13 List (java.util.List)11 Assertions.assertThatExceptionOfType (org.assertj.core.api.Assertions.assertThatExceptionOfType)9 Collections (java.util.Collections)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)8 Nullable (javax.annotation.Nullable)8 Flux (reactor.core.publisher.Flux)8 StepVerifier (reactor.test.StepVerifier)8