Search in sources :

Example 6 with ReactiveAuthenticationManager

use of org.springframework.security.authentication.ReactiveAuthenticationManager in project spring-security by spring-projects.

the class ServerHttpSecurityTests method basicWithCustomAuthenticationManager.

@Test
public void basicWithCustomAuthenticationManager() {
    ReactiveAuthenticationManager customAuthenticationManager = mock(ReactiveAuthenticationManager.class);
    given(customAuthenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("rob", "rob", "ROLE_USER", "ROLE_ADMIN")));
    // @formatter:off
    SecurityWebFilterChain securityFilterChain = this.http.httpBasic().authenticationManager(customAuthenticationManager).and().build();
    // @formatter:on
    WebFilterChainProxy springSecurityFilterChain = new WebFilterChainProxy(securityFilterChain);
    // @formatter:off
    WebTestClient client = WebTestClientBuilder.bindToWebFilters(springSecurityFilterChain).build();
    client.get().uri("/").headers((headers) -> headers.setBasicAuth("rob", "rob")).exchange().expectStatus().isOk().expectBody(String.class).consumeWith((b) -> assertThat(b.getResponseBody()).isEqualTo("ok"));
    // @formatter:on
    verifyZeroInteractions(this.authenticationManager);
}
Also used : ServerAuthorizationRequestRepository(org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ServerLogoutHandler(org.springframework.security.web.server.authentication.logout.ServerLogoutHandler) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) LogoutWebFilter(org.springframework.security.web.server.authentication.logout.LogoutWebFilter) WebFilter(org.springframework.web.server.WebFilter) BDDMockito.given(org.mockito.BDDMockito.given) HttpBasicServerAuthenticationEntryPoint(org.springframework.security.web.server.authentication.HttpBasicServerAuthenticationEntryPoint) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) SecurityContextServerWebExchangeWebFilter(org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter) WebSessionServerSecurityContextRepository(org.springframework.security.web.server.context.WebSessionServerSecurityContextRepository) HttpHeaders(org.apache.http.HttpHeaders) OAuth2LoginAuthenticationWebFilter(org.springframework.security.oauth2.client.web.server.authentication.OAuth2LoginAuthenticationWebFilter) WebFilterChain(org.springframework.web.server.WebFilterChain) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) ServerHttpSecurityConfigurationBuilder(org.springframework.security.config.annotation.web.reactive.ServerHttpSecurityConfigurationBuilder) ServerAuthenticationEntryPoint(org.springframework.security.web.server.ServerAuthenticationEntryPoint) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) EntityExchangeResult(org.springframework.test.web.reactive.server.EntityExchangeResult) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) SecurityContext(org.springframework.security.core.context.SecurityContext) Optional(java.util.Optional) CsrfWebFilter(org.springframework.security.web.server.csrf.CsrfWebFilter) Authentication(org.springframework.security.core.Authentication) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) TestPublisher(reactor.test.publisher.TestPublisher) Mock(org.mockito.Mock) TestOAuth2AuthorizationRequests(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests) Mockito.spy(org.mockito.Mockito.spy) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) SecurityContextServerLogoutHandler(org.springframework.security.web.server.authentication.logout.SecurityContextServerLogoutHandler) ArgumentCaptor(org.mockito.ArgumentCaptor) WebSessionServerRequestCache(org.springframework.security.web.server.savedrequest.WebSessionServerRequestCache) GetMapping(org.springframework.web.bind.annotation.GetMapping) AnonymousAuthenticationWebFilterTests(org.springframework.security.web.server.authentication.AnonymousAuthenticationWebFilterTests) WebTestClientBuilder(org.springframework.security.test.web.reactive.server.WebTestClientBuilder) ServerSecurityContextRepository(org.springframework.security.web.server.context.ServerSecurityContextRepository) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) ServerRequestCache(org.springframework.security.web.server.savedrequest.ServerRequestCache) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) X509PrincipalExtractor(org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) Mono(reactor.core.publisher.Mono) WebFilterChainProxy(org.springframework.security.web.server.WebFilterChainProxy) CsrfServerLogoutHandler(org.springframework.security.web.server.csrf.CsrfServerLogoutHandler) Mockito.verify(org.mockito.Mockito.verify) HttpStatus(org.springframework.http.HttpStatus) FluxExchangeResult(org.springframework.test.web.reactive.server.FluxExchangeResult) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) HttpStatusServerEntryPoint(org.springframework.security.web.server.authentication.HttpStatusServerEntryPoint) ServerCsrfTokenRepository(org.springframework.security.web.server.csrf.ServerCsrfTokenRepository) ServerX509AuthenticationConverter(org.springframework.security.web.server.authentication.ServerX509AuthenticationConverter) DelegatingServerLogoutHandler(org.springframework.security.web.server.authentication.logout.DelegatingServerLogoutHandler) Customizer.withDefaults(org.springframework.security.config.Customizer.withDefaults) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) WebFilterChainProxy(org.springframework.security.web.server.WebFilterChainProxy) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) Test(org.junit.jupiter.api.Test)

Example 7 with ReactiveAuthenticationManager

use of org.springframework.security.authentication.ReactiveAuthenticationManager in project spring-security by spring-projects.

the class ServerHttpSecurityTests method addsX509FilterWhenX509AuthenticationIsConfigured.

@Test
@SuppressWarnings("unchecked")
public void addsX509FilterWhenX509AuthenticationIsConfigured() {
    X509PrincipalExtractor mockExtractor = mock(X509PrincipalExtractor.class);
    ReactiveAuthenticationManager mockAuthenticationManager = mock(ReactiveAuthenticationManager.class);
    this.http.x509().principalExtractor(mockExtractor).authenticationManager(mockAuthenticationManager).and();
    SecurityWebFilterChain securityWebFilterChain = this.http.build();
    WebFilter x509WebFilter = securityWebFilterChain.getWebFilters().filter(this::isX509Filter).blockFirst();
    assertThat(x509WebFilter).isNotNull();
}
Also used : ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) LogoutWebFilter(org.springframework.security.web.server.authentication.logout.LogoutWebFilter) WebFilter(org.springframework.web.server.WebFilter) SecurityContextServerWebExchangeWebFilter(org.springframework.security.web.server.context.SecurityContextServerWebExchangeWebFilter) OAuth2LoginAuthenticationWebFilter(org.springframework.security.oauth2.client.web.server.authentication.OAuth2LoginAuthenticationWebFilter) CsrfWebFilter(org.springframework.security.web.server.csrf.CsrfWebFilter) X509PrincipalExtractor(org.springframework.security.web.authentication.preauth.x509.X509PrincipalExtractor) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) Test(org.junit.jupiter.api.Test)

Example 8 with ReactiveAuthenticationManager

use of org.springframework.security.authentication.ReactiveAuthenticationManager in project spring-security by spring-projects.

the class OAuth2ResourceServerSpecTests method getWhenUsingCustomAuthenticationManagerInLambdaThenUsesItAccordingly.

@Test
public void getWhenUsingCustomAuthenticationManagerInLambdaThenUsesItAccordingly() {
    this.spring.register(CustomAuthenticationManagerInLambdaConfig.class).autowire();
    ReactiveAuthenticationManager authenticationManager = this.spring.getContext().getBean(ReactiveAuthenticationManager.class);
    given(authenticationManager.authenticate(any(Authentication.class))).willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("mock-failure"))));
    // @formatter:off
    this.client.get().headers((headers) -> headers.setBearerAuth(this.messageReadToken)).exchange().expectStatus().isUnauthorized().expectHeader().value(HttpHeaders.WWW_AUTHENTICATE, startsWith("Bearer error=\"mock-failure\""));
// @formatter:on
}
Also used : JwtAuthenticationConverter(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Autowired(org.springframework.beans.factory.annotation.Autowired) CoreMatchers.startsWith(org.hamcrest.CoreMatchers.startsWith) RSAPublicKey(java.security.interfaces.RSAPublicKey) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) RSAPublicKeySpec(java.security.spec.RSAPublicKeySpec) MockWebServer(okhttp3.mockwebserver.MockWebServer) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) BigInteger(java.math.BigInteger) ReactiveAuthenticationManagerResolver(org.springframework.security.authentication.ReactiveAuthenticationManagerResolver) Jwt(org.springframework.security.oauth2.jwt.Jwt) HttpHeaders(org.apache.http.HttpHeaders) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) PostMapping(org.springframework.web.bind.annotation.PostMapping) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MediaType(org.springframework.http.MediaType) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) PreDestroy(jakarta.annotation.PreDestroy) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) KeyFactory(java.security.KeyFactory) Test(org.junit.jupiter.api.Test) Base64(java.util.Base64) Stream(java.util.stream.Stream) AbstractAuthenticationToken(org.springframework.security.authentication.AbstractAuthenticationToken) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Optional(java.util.Optional) MockResponse(okhttp3.mockwebserver.MockResponse) Authentication(org.springframework.security.core.Authentication) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ReactiveJwtAuthenticationConverterAdapter(org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverterAdapter) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) ReactiveJwtAuthenticationConverter(org.springframework.security.oauth2.server.resource.authentication.ReactiveJwtAuthenticationConverter) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) DispatcherHandler(org.springframework.web.reactive.DispatcherHandler) ServerWebExchange(org.springframework.web.server.ServerWebExchange) Value(org.springframework.beans.factory.annotation.Value) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) EnableWebFlux(org.springframework.web.reactive.config.EnableWebFlux) Dispatcher(okhttp3.mockwebserver.Dispatcher) BeanCreationException(org.springframework.beans.factory.BeanCreationException) EnableWebFluxSecurity(org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) GetMapping(org.springframework.web.bind.annotation.GetMapping) NoUniqueBeanDefinitionException(org.springframework.beans.factory.NoUniqueBeanDefinitionException) Converter(org.springframework.core.convert.converter.Converter) IOException(java.io.IOException) Mono(reactor.core.publisher.Mono) ApplicationContext(org.springframework.context.ApplicationContext) Mockito.verify(org.mockito.Mockito.verify) HttpStatus(org.springframework.http.HttpStatus) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) HttpStatusServerEntryPoint(org.springframework.security.web.server.authentication.HttpStatusServerEntryPoint) SpringTestContext(org.springframework.security.config.test.SpringTestContext) NoSuchBeanDefinitionException(org.springframework.beans.factory.NoSuchBeanDefinitionException) HttpStatusServerAccessDeniedHandler(org.springframework.security.web.server.authorization.HttpStatusServerAccessDeniedHandler) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext) SpringTestContextExtension(org.springframework.security.config.test.SpringTestContextExtension) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Bean(org.springframework.context.annotation.Bean) BearerTokenAuthenticationToken(org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) Authentication(org.springframework.security.core.Authentication) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Test(org.junit.jupiter.api.Test)

Example 9 with ReactiveAuthenticationManager

use of org.springframework.security.authentication.ReactiveAuthenticationManager in project spring-security by spring-projects.

the class FormLoginTests method customAuthenticationManager.

@Test
public void customAuthenticationManager() {
    ReactiveAuthenticationManager defaultAuthenticationManager = mock(ReactiveAuthenticationManager.class);
    ReactiveAuthenticationManager customAuthenticationManager = mock(ReactiveAuthenticationManager.class);
    given(defaultAuthenticationManager.authenticate(any())).willThrow(new RuntimeException("should not interact with default auth manager"));
    given(customAuthenticationManager.authenticate(any())).willReturn(Mono.just(new TestingAuthenticationToken("user", "password", "ROLE_USER", "ROLE_ADMIN")));
    // @formatter:off
    SecurityWebFilterChain securityWebFilter = this.http.authenticationManager(defaultAuthenticationManager).formLogin().authenticationManager(customAuthenticationManager).and().build();
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(securityWebFilter).build();
    WebDriver driver = WebTestClientHtmlUnitDriverBuilder.webTestClientSetup(webTestClient).build();
    // @formatter:on
    DefaultLoginPage loginPage = DefaultLoginPage.to(driver).assertAt();
    // @formatter:off
    HomePage homePage = loginPage.loginForm().username("user").password("password").submit(HomePage.class);
    // @formatter:on
    homePage.assertAt();
    verifyZeroInteractions(defaultAuthenticationManager);
}
Also used : WebDriver(org.openqa.selenium.WebDriver) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) Test(org.junit.jupiter.api.Test)

Example 10 with ReactiveAuthenticationManager

use of org.springframework.security.authentication.ReactiveAuthenticationManager in project spring-security by spring-projects.

the class ServerWebExchangeDelegatingReactiveAuthenticationManagerResolverTests method resolveWhenDoesNotMatchThenReturnsDefaultReactiveAuthenticationManager.

@Test
public void resolveWhenDoesNotMatchThenReturnsDefaultReactiveAuthenticationManager() {
    ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver resolver = ServerWebExchangeDelegatingReactiveAuthenticationManagerResolver.builder().add(new PathPatternParserServerWebExchangeMatcher("/one/**"), this.one).add(new PathPatternParserServerWebExchangeMatcher("/two/**"), this.two).build();
    MockServerHttpRequest request = MockServerHttpRequest.get("/wrong/location").build();
    ReactiveAuthenticationManager authenticationManager = resolver.resolve(MockServerWebExchange.from(request)).block();
    Authentication authentication = new TestingAuthenticationToken("principal", "creds");
    assertThatExceptionOfType(AuthenticationServiceException.class).isThrownBy(() -> authenticationManager.authenticate(authentication).block());
}
Also used : PathPatternParserServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.PathPatternParserServerWebExchangeMatcher) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) MockServerHttpRequest(org.springframework.mock.http.server.reactive.MockServerHttpRequest) Authentication(org.springframework.security.core.Authentication) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) AuthenticationServiceException(org.springframework.security.authentication.AuthenticationServiceException) Test(org.junit.jupiter.api.Test)

Aggregations

ReactiveAuthenticationManager (org.springframework.security.authentication.ReactiveAuthenticationManager)20 Test (org.junit.jupiter.api.Test)19 Authentication (org.springframework.security.core.Authentication)13 SecurityWebFilterChain (org.springframework.security.web.server.SecurityWebFilterChain)13 BDDMockito.given (org.mockito.BDDMockito.given)12 Mono (reactor.core.publisher.Mono)12 WebTestClient (org.springframework.test.web.reactive.server.WebTestClient)11 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)10 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)10 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)10 Mockito.mock (org.mockito.Mockito.mock)10 Mockito.verify (org.mockito.Mockito.verify)10 GetMapping (org.springframework.web.bind.annotation.GetMapping)10 RestController (org.springframework.web.bind.annotation.RestController)10 TestingAuthenticationToken (org.springframework.security.authentication.TestingAuthenticationToken)9 MockResponse (okhttp3.mockwebserver.MockResponse)8 MockWebServer (okhttp3.mockwebserver.MockWebServer)8 Autowired (org.springframework.beans.factory.annotation.Autowired)8 ApplicationContext (org.springframework.context.ApplicationContext)8 Bean (org.springframework.context.annotation.Bean)8