Search in sources :

Example 11 with MockServerWebExchange

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

the class SwitchUserWebFilterTests method switchUserWhenUsernameIsMissingThenThrowException.

@Test
public void switchUserWhenUsernameIsMissingThenThrowException() {
    final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate"));
    final WebFilterChain chain = mock(WebFilterChain.class);
    final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
    assertThatIllegalArgumentException().isThrownBy(() -> {
        Context securityContextHolder = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext));
        this.switchUserWebFilter.filter(exchange, chain).subscriberContext(securityContextHolder).block();
    }).withMessage("The userName can not be null.");
    verifyNoInteractions(chain);
}
Also used : Context(reactor.util.context.Context) SecurityContext(org.springframework.security.core.context.SecurityContext) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) WebFilterChain(org.springframework.web.server.WebFilterChain) Authentication(org.springframework.security.core.Authentication) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) Test(org.junit.jupiter.api.Test)

Example 12 with MockServerWebExchange

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

the class SwitchUserWebFilterTests method setExitUserMatcherWhenDefinedThenChangeDefaultValue.

@Test
public void setExitUserMatcherWhenDefinedThenChangeDefaultValue() {
    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();
    final ServerWebExchangeMatcher newExitUserMatcher = ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/exit-url");
    this.switchUserWebFilter.setExitUserMatcher(newExitUserMatcher);
    final ServerWebExchangeMatcher currentExitUserMatcher = (ServerWebExchangeMatcher) ReflectionTestUtils.getField(this.switchUserWebFilter, "exitUserMatcher");
    assertThat(currentExitUserMatcher).isSameAs(newExitUserMatcher);
}
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 13 with MockServerWebExchange

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

the class SwitchUserWebFilterTests method switchUserWhenUserAlreadySwitchedThenExitSwitchAndSwitchAgain.

@Test
public void switchUserWhenUserAlreadySwitchedThenExitSwitchAndSwitchAgain() {
    final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal", "origCredentials");
    final GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority(SwitchUserWebFilter.ROLE_PREVIOUS_ADMINISTRATOR, originalAuthentication);
    final Authentication switchUserAuthentication = new UsernamePasswordAuthenticationToken("switchPrincipal", "switchCredentials", Collections.singleton(switchAuthority));
    final SecurityContextImpl securityContext = new SecurityContextImpl(switchUserAuthentication);
    final String targetUsername = "newSwitchPrincipal";
    final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
    final WebFilterChain chain = mock(WebFilterChain.class);
    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());
    given(this.userDetailsService.findByUsername(targetUsername)).willReturn(Mono.just(switchUserDetails(targetUsername, true)));
    this.switchUserWebFilter.filter(exchange, chain).subscriberContext(ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext))).block();
    final ArgumentCaptor<Authentication> authenticationCaptor = ArgumentCaptor.forClass(Authentication.class);
    verify(this.successHandler).onAuthenticationSuccess(any(WebFilterExchange.class), authenticationCaptor.capture());
    final Authentication secondSwitchUserAuthentication = authenticationCaptor.getValue();
    assertThat(secondSwitchUserAuthentication.getName()).isEqualTo(targetUsername);
    assertThat(secondSwitchUserAuthentication.getAuthorities().stream().filter((a) -> a instanceof SwitchUserGrantedAuthority).map((a) -> ((SwitchUserGrantedAuthority) a).getSource()).map(Principal::getName).findFirst().orElse(null)).isEqualTo(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) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) SwitchUserGrantedAuthority(org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) SwitchUserGrantedAuthority(org.springframework.security.web.authentication.switchuser.SwitchUserGrantedAuthority) WebFilterExchange(org.springframework.security.web.server.WebFilterExchange) 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)

Example 14 with MockServerWebExchange

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

the class SwitchUserWebFilterTests method switchUserWhenFailureHandlerNotDefinedThenReturnError.

@Test
public void switchUserWhenFailureHandlerNotDefinedThenReturnError() {
    this.switchUserWebFilter = new SwitchUserWebFilter(this.userDetailsService, this.successHandler, null);
    final String targetUsername = "TEST_USERNAME";
    final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/login/impersonate?username={targetUser}", targetUsername));
    final WebFilterChain chain = mock(WebFilterChain.class);
    final SecurityContextImpl securityContext = new SecurityContextImpl(mock(Authentication.class));
    final UserDetails switchUserDetails = switchUserDetails(targetUsername, false);
    given(this.userDetailsService.findByUsername(any(String.class))).willReturn(Mono.just(switchUserDetails));
    assertThatExceptionOfType(DisabledException.class).isThrownBy(() -> {
        Context securityContextHolder = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext));
        this.switchUserWebFilter.filter(exchange, chain).subscriberContext(securityContextHolder).block();
    });
    verifyNoInteractions(chain);
}
Also used : Context(reactor.util.context.Context) SecurityContext(org.springframework.security.core.context.SecurityContext) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) UserDetails(org.springframework.security.core.userdetails.UserDetails) WebFilterChain(org.springframework.web.server.WebFilterChain) Authentication(org.springframework.security.core.Authentication) DisabledException(org.springframework.security.authentication.DisabledException) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) Test(org.junit.jupiter.api.Test)

Example 15 with MockServerWebExchange

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

the class SwitchUserWebFilterTests method exitSwitchWhenUserNotSwitchedThenThrowError.

@Test
public void exitSwitchWhenUserNotSwitchedThenThrowError() {
    final MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("/logout/impersonate"));
    final Authentication originalAuthentication = new UsernamePasswordAuthenticationToken("origPrincipal", "origCredentials");
    final WebFilterChain chain = mock(WebFilterChain.class);
    final SecurityContextImpl securityContext = new SecurityContextImpl(originalAuthentication);
    assertThatExceptionOfType(AuthenticationCredentialsNotFoundException.class).isThrownBy(() -> {
        Context securityContextHolder = ReactiveSecurityContextHolder.withSecurityContext(Mono.just(securityContext));
        this.switchUserWebFilter.filter(exchange, chain).subscriberContext(securityContextHolder).block();
    }).withMessage("Could not find original Authentication object");
    verifyNoInteractions(chain);
}
Also used : Context(reactor.util.context.Context) SecurityContext(org.springframework.security.core.context.SecurityContext) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) WebFilterChain(org.springframework.web.server.WebFilterChain) Authentication(org.springframework.security.core.Authentication) MockServerWebExchange(org.springframework.mock.web.server.MockServerWebExchange) UsernamePasswordAuthenticationToken(org.springframework.security.authentication.UsernamePasswordAuthenticationToken) 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