Search in sources :

Example 6 with MockServerWebExchange

use of org.springframework.mock.web.server.MockServerWebExchange in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeGrantWebFilterTests method filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException.

// gh-8609
@Test
public void filterWhenAuthenticationManagerThrowsOAuth2AuthorizationExceptionThenMappedToOAuth2AuthenticationException() {
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
    given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
    MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
    OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
    given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
    given(this.authenticationManager.authenticate(any())).willReturn(Mono.error(new OAuth2AuthorizationException(new OAuth2Error("authorization_error"))));
    MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
    MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
    DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
    assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.filter.filter(exchange, chain).block()).satisfies((ex) -> assertThat(ex.getError()).extracting("errorCode").isEqualTo("authorization_error"));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) DefaultWebFilterChain(org.springframework.web.server.handler.DefaultWebFilterChain) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 7 with MockServerWebExchange

use of org.springframework.mock.web.server.MockServerWebExchange in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeGrantWebFilterTests method filterWhenNotMatchThenAuthenticationManagerNotCalled.

@Test
public void filterWhenNotMatchThenAuthenticationManagerNotCalled() {
    MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/"));
    DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
    this.filter.filter(exchange, chain).block();
    verifyNoInteractions(this.authenticationManager);
}
Also used : MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) DefaultWebFilterChain(org.springframework.web.server.handler.DefaultWebFilterChain) Test(org.junit.jupiter.api.Test)

Example 8 with MockServerWebExchange

use of org.springframework.mock.web.server.MockServerWebExchange in project spring-security by spring-projects.

the class OAuth2AuthorizationCodeGrantWebFilterTests method filterWhenMatchThenAuthorizedClientSaved.

@Test
public void filterWhenMatchThenAuthorizedClientSaved() {
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().build();
    given(this.clientRegistrationRepository.findByRegistrationId(any())).willReturn(Mono.just(clientRegistration));
    MockServerHttpRequest authorizationRequest = createAuthorizationRequest("/authorization/callback");
    OAuth2AuthorizationRequest oauth2AuthorizationRequest = createOAuth2AuthorizationRequest(authorizationRequest, clientRegistration);
    given(this.authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
    given(this.authorizationRequestRepository.removeAuthorizationRequest(any())).willReturn(Mono.just(oauth2AuthorizationRequest));
    given(this.authorizedClientRepository.saveAuthorizedClient(any(), any(), any())).willReturn(Mono.empty());
    given(this.authenticationManager.authenticate(any())).willReturn(Mono.just(TestOAuth2AuthorizationCodeAuthenticationTokens.authenticated()));
    MockServerHttpRequest authorizationResponse = createAuthorizationResponse(authorizationRequest);
    MockServerWebExchange exchange = MockServerWebExchange.from(authorizationResponse);
    DefaultWebFilterChain chain = new DefaultWebFilterChain((e) -> e.getResponse().setComplete(), Collections.emptyList());
    this.filter.filter(exchange, chain).block();
    verify(this.authorizedClientRepository).saveAuthorizedClient(any(), any(AnonymousAuthenticationToken.class), any());
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) DefaultWebFilterChain(org.springframework.web.server.handler.DefaultWebFilterChain) AnonymousAuthenticationToken(org.springframework.security.authentication.AnonymousAuthenticationToken) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Test(org.junit.jupiter.api.Test)

Example 9 with MockServerWebExchange

use of org.springframework.mock.web.server.MockServerWebExchange in project spring-security by spring-projects.

the class SwitchUserWebFilterTests method setExitUserUrlWhenDefinedThenChangeDefaultValue.

@Test
public void setExitUserUrlWhenDefinedThenChangeDefaultValue() {
    final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/logout/impersonate"));
    final ServerWebExchangeMatcher oldExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils.getField(this.switchUserWebFilter, "exitUserMatcher");
    assertThat(oldExitUserMatcher.matches(exchange).block().isMatch()).isTrue();
    this.switchUserWebFilter.setExitUserUrl("/exit-url");
    final MockServerWebExchange newExchange = MockServerWebExchange.from(MockServerHttpRequest.post("/exit-url"));
    final ServerWebExchangeMatcher newExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils.getField(this.switchUserWebFilter, "exitUserMatcher");
    assertThat(newExitUserMatcher.matches(newExchange).block().isMatch()).isTrue();
}
Also used : ServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) Test(org.junit.jupiter.api.Test)

Example 10 with MockServerWebExchange

use of org.springframework.mock.web.server.MockServerWebExchange in project spring-security by spring-projects.

the class SwitchUserWebFilterTests method switchUser.

@Test
public void switchUser() {
    final String targetUsername = "TEST_USERNAME";
    final UserDetails switchUserDetails = switchUserDetails(targetUsername, true);
    final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
    final WebFilterChain chain = mock(WebFilterChain.class);
    final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("principal", "credentials");
    final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
    given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails));
    given(this.serverSecurityContextRepository.save(eq(exchange), any(SecurityContext.class))).willReturn(Mono.empty());
    given(this.successHandler.onAuthenticationSuccess(any(WebFilterExchange.class), any(Authentication.class))).willReturn(Mono.empty());
    this.switchUserWebFilter.filter(exchange, chain).subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
    verifyNoInteractions(chain);
    verify(this.userDetailsService).findByUsername(targetUsername);
    final ArgumentCaptor<SecurityContext> securityContextCaptor = ArgumentCaptor.forClass(SecurityContext.class);
    verify(this.serverSecurityContextRepository).save(eq(exchange), securityContextCaptor.capture());
    final SecurityContext savedSecurityContext = securityContextCaptor.getValue();
    final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
    final Authentication switchUserAuthentication = authenticationCaptor.getValue();
    assertThat(switchUserAuthentication).isSameAs(savedSecurityContext.getAuthentication());
    assertThat(switchUserAuthentication.getName()).isEqualTo(targetUsername);
    assertThat(switchUserAuthentication.getAuthorities()).anyMatch(SwitchUserGrantedAuthority.class::isInstance);
    assertThat(switchUserAuthentication.getAuthorities()).anyMatch((a) -> a.getAuthority().contains(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR));
    assertThat(switchUserAuthentication.getAuthorities().stream().filter((a) -> a instanceof SwitchUserGrantedAuthority).map((a) -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName)).contains(originalAuthentication.getName());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) ServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher) Mock(org.mockito.Mock) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) User(org.springframework.security.core.userdetails.User) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) WebFilterExchange(org.springframework.security.web.server.WebFilterExchange) ArgumentCaptor(org.mockito.ArgumentCaptor) ReactiveSecurityContextHolder(org.springframework.security.core.context.ReactiveSecurityContextHolder) ReactiveUserDetailsService(org.springframework.security.core.userdetails.ReactiveUserDetailsService) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) DisabledException(org.springframework.security.authentication.DisabledException) UserDetails(org.springframework.security.core.userdetails.UserDetails) AuthenticationCredentialsNotFoundException(org.springframework.security.authentication.AuthenticationCredentialsNotFoundException) WebSessionServerSecurityContextRepository(org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository) WebFilterChain(org.springframework.web.server.WebFilterChain) ServerSecurityContextRepository(org.springframework.security.web.server.context.ServerSecurityContextRepository) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) Context(reactor.util.context.Context) HttpMethod(org.springframework.http.HttpMethod) ServerWebExchangeMatchers(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) Mono(reactor.core.publisher.Mono) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Principal(java.security.Principal) SwitchUserGrantedAuthority(org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority) SecurityContext(org.springframework.security.core.context.SecurityContext) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) AccountStatusUserDetailsChecker(org.springframework.security.authentication.AccountStatusUserDetailsChecker) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) Authentication(org.springframework.security.core.Authentication) Collections(java.util.Collections) Mockito.mock(org.mockito.Mockito.mock) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) WebFilterExchange(org.springframework.security.web.server.WebFilterExchange) SwitchUserGrantedAuthority(org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority) UserDetails(org.springframework.security.core.userdetails.UserDetails) WebFilterChain(org.springframework.web.server.WebFilterChain) Authentication(org.springframework.security.core.Authentication) SecurityContext(org.springframework.security.core.context.SecurityContext) Principal(java.security.Principal) Test(org.junit.jupiter.api.Test)

Aggregations

MockServerWebExchange (org.springframework.mock.web.server.MockServerWebExchange)94 Test (org.junit.jupiter.api.Test)81 MockServerHttpRequest (org.springframework.mock.http.server.reactive.MockServerHttpRequest)44 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)27 Mono (reactor.core.publisher.Mono)26 BeforeEach (org.junit.jupiter.api.BeforeEach)22 StepVerifier (reactor.test.StepVerifier)21 ServerWebExchange (org.springframework.web.server.ServerWebExchange)15 Duration (java.time.Duration)14 ErrorAttributes (org.springframework.boot.web.reactive.error.ErrorAttributes)13 HandlerMethod (org.springframework.web.method.HandlerMethod)13 Timed (io.micrometer.core.annotation.Timed)12 MockClock (io.micrometer.core.instrument.MockClock)12 Tag (io.micrometer.core.instrument.Tag)12 SimpleConfig (io.micrometer.core.instrument.simple.SimpleConfig)12 SimpleMeterRegistry (io.micrometer.core.instrument.simple.SimpleMeterRegistry)12 EOFException (java.io.EOFException)12 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)12 AutoTimer (org.springframework.boot.actuate.metrics.AutoTimer)12 ResponseCookie (org.springframework.http.ResponseCookie)12