Search in sources :

Example 11 with ReactiveAuthenticationManager

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

the class OAuth2LoginTests method oauth2LoginFailsWhenCustomObjectsThenUsed.

@Test
public void oauth2LoginFailsWhenCustomObjectsThenUsed() {
    this.spring.register(OAuth2LoginWithSingleClientRegistrations.class, OAuth2LoginMockAuthenticationManagerConfig.class).autowire();
    String redirectLocation = "/custom-redirect-location";
    String failureRedirectLocation = "/failure-redirect-location";
    // @formatter:off
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(this.springSecurity).build();
    // @formatter:on
    OAuth2LoginMockAuthenticationManagerConfig config = this.spring.getContext().getBean(OAuth2LoginMockAuthenticationManagerConfig.class);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    ReactiveAuthenticationManager manager = config.manager;
    ServerWebExchangeMatcher matcher = config.matcher;
    ServerOAuth2AuthorizationRequestResolver resolver = config.resolver;
    ServerAuthenticationSuccessHandler successHandler = config.successHandler;
    ServerAuthenticationFailureHandler failureHandler = config.failureHandler;
    given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
    given(manager.authenticate(any())).willReturn(Mono.error(new OAuth2AuthenticationException(new OAuth2Error("error"), "message")));
    given(matcher.matches(any())).willReturn(ServerWebExchangeMatcher.MatchResult.match());
    given(resolver.resolve(any())).willReturn(Mono.empty());
    given(successHandler.onAuthenticationSuccess(any(), any())).willAnswer((Answer<Mono<Void>>) (invocation) -> {
        WebFilterExchange webFilterExchange = invocation.getArgument(0);
        Authentication authentication = invocation.getArgument(1);
        return new RedirectServerAuthenticationSuccessHandler(redirectLocation).onAuthenticationSuccess(webFilterExchange, authentication);
    });
    given(failureHandler.onAuthenticationFailure(any(), any())).willAnswer((Answer<Mono<Void>>) (invocation) -> {
        WebFilterExchange webFilterExchange = invocation.getArgument(0);
        AuthenticationException authenticationException = invocation.getArgument(1);
        return new RedirectServerAuthenticationFailureHandler(failureRedirectLocation).onAuthenticationFailure(webFilterExchange, authenticationException);
    });
    // @formatter:off
    webTestClient.get().uri("/login/oauth2/code/github").exchange().expectStatus().is3xxRedirection().expectHeader().valueEquals("Location", failureRedirectLocation);
    // @formatter:on
    verify(converter).convert(any());
    verify(manager).authenticate(any());
    verify(matcher).matches(any());
    verify(resolver).resolve(any());
    verify(failureHandler).onAuthenticationFailure(any(), any());
}
Also used : ServerAuthorizationRequestRepository(org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Autowired(org.springframework.beans.factory.annotation.Autowired) WebHandler(org.springframework.web.server.WebHandler) WebTestClientHtmlUnitDriverBuilder(org.springframework.security.htmlunit.server.WebTestClientHtmlUnitDriverBuilder) WebFilterExchange(org.springframework.security.web.server.WebFilterExchange) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ReactiveUserDetailsService(org.springframework.security.core.userdetails.ReactiveUserDetailsService) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) TestOidcUsers(org.springframework.security.oauth2.core.oidc.user.TestOidcUsers) WebFilter(org.springframework.web.server.WebFilter) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) AuthenticationException(org.springframework.security.core.AuthenticationException) Jwt(org.springframework.security.oauth2.jwt.Jwt) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) WebFilterChain(org.springframework.web.server.WebFilterChain) OidcClientInitiatedServerLogoutSuccessHandler(org.springframework.security.oauth2.client.oidc.web.server.logout.OidcClientInitiatedServerLogoutSuccessHandler) TestOAuth2AuthorizationExchanges(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationExchanges) ReactiveAuthenticationTestConfiguration(org.springframework.security.config.users.ReactiveAuthenticationTestConfiguration) HttpHeaders(org.springframework.http.HttpHeaders) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) ServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) RestController(org.springframework.web.bind.annotation.RestController) Test(org.junit.jupiter.api.Test) Configuration(org.springframework.context.annotation.Configuration) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) SecurityContext(org.springframework.security.core.context.SecurityContext) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) ReactiveJwtDecoderFactory(org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ServerOAuth2AuthorizationRequestResolver(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizationRequestResolver) ServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) WebDriver(org.openqa.selenium.WebDriver) IdTokenClaimNames(org.springframework.security.oauth2.core.oidc.IdTokenClaimNames) TestOAuth2AuthorizationRequests(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests) OidcParameterNames(org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) OidcAuthorizationCodeReactiveAuthenticationManager(org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeReactiveAuthenticationManager) RedirectServerAuthenticationFailureHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationFailureHandler) ServerWebExchange(org.springframework.web.server.ServerWebExchange) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) Answer(org.mockito.stubbing.Answer) SecurityContextServerLogoutHandler(org.springframework.security.web.server.authentication.logout.SecurityContextServerLogoutHandler) EnableWebFlux(org.springframework.web.reactive.config.EnableWebFlux) EnableWebFluxSecurity(org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity) CommonOAuth2Provider(org.springframework.security.config.oauth2.client.CommonOAuth2Provider) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) JwtValidationException(org.springframework.security.oauth2.jwt.JwtValidationException) GetMapping(org.springframework.web.bind.annotation.GetMapping) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestOAuth2Users(org.springframework.security.oauth2.core.user.TestOAuth2Users) WebTestClientBuilder(org.springframework.security.test.web.reactive.server.WebTestClientBuilder) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ServerSecurityContextRepository(org.springframework.security.web.server.context.ServerSecurityContextRepository) SecurityContextImpl(org.springframework.security.core.context.SecurityContextImpl) ServerRequestCache(org.springframework.security.web.server.savedrequest.ServerRequestCache) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) OAuth2AuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ApplicationContext(org.springframework.context.ApplicationContext) WebFilterChainProxy(org.springframework.security.web.server.WebFilterChainProxy) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Mockito.verify(org.mockito.Mockito.verify) InMemoryReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) SpringTestContext(org.springframework.security.config.test.SpringTestContext) TestOAuth2AuthorizationResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses) SpringTestContextExtension(org.springframework.security.config.test.SpringTestContextExtension) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Bean(org.springframework.context.annotation.Bean) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) UserDetailsRepositoryReactiveAuthenticationManager(org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager) ServerAuthenticationFailureHandler(org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) OidcAuthorizationCodeReactiveAuthenticationManager(org.springframework.security.oauth2.client.oidc.authentication.OidcAuthorizationCodeReactiveAuthenticationManager) UserDetailsRepositoryReactiveAuthenticationManager(org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager) RedirectServerAuthenticationFailureHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationFailureHandler) ServerAuthenticationFailureHandler(org.springframework.security.web.server.authentication.ServerAuthenticationFailureHandler) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) AuthenticationException(org.springframework.security.core.AuthenticationException) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) ServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) Mono(reactor.core.publisher.Mono) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) WebFilterExchange(org.springframework.security.web.server.WebFilterExchange) RedirectServerAuthenticationFailureHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationFailureHandler) Authentication(org.springframework.security.core.Authentication) ServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) ServerOAuth2AuthorizationRequestResolver(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizationRequestResolver) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) Test(org.junit.jupiter.api.Test)

Example 12 with ReactiveAuthenticationManager

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

the class OAuth2ClientSpecTests method oauth2ClientWhenCustomObjectsThenUsed.

@Test
public void oauth2ClientWhenCustomObjectsThenUsed() {
    this.spring.register(ClientRegistrationConfig.class, OAuth2ClientCustomConfig.class, AuthorizedClientController.class).autowire();
    OAuth2ClientCustomConfig config = this.spring.getContext().getBean(OAuth2ClientCustomConfig.class);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    ReactiveAuthenticationManager manager = config.manager;
    ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = config.authorizationRequestRepository;
    ServerRequestCache requestCache = config.requestCache;
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().redirectUri("/authorize/oauth2/code/registration-id").build();
    OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().redirectUri("/authorize/oauth2/code/registration-id").build();
    OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse);
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
    OAuth2AuthorizationCodeAuthenticationToken result = new OAuth2AuthorizationCodeAuthenticationToken(this.registration, authorizationExchange, accessToken);
    given(authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(authorizationRequest));
    given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
    given(manager.authenticate(any())).willReturn(Mono.just(result));
    given(requestCache.getRedirectUri(any())).willReturn(Mono.just(URI.create("/saved-request")));
    // @formatter:off
    this.client.get().uri((uriBuilder) -> uriBuilder.path("/authorize/oauth2/code/registration-id").queryParam(OAuth2ParameterNames.CODE, "code").queryParam(OAuth2ParameterNames.STATE, "state").build()).exchange().expectStatus().is3xxRedirection();
    // @formatter:on
    verify(converter).convert(any());
    verify(manager).authenticate(any());
    verify(requestCache).getRedirectUri(any());
}
Also used : ServerAuthorizationRequestRepository(org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) TestOAuth2AuthorizationRequests(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests) Autowired(org.springframework.beans.factory.annotation.Autowired) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) EnableWebFlux(org.springframework.web.reactive.config.EnableWebFlux) EnableWebFluxSecurity(org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity) BDDMockito.given(org.mockito.BDDMockito.given) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) GetMapping(org.springframework.web.bind.annotation.GetMapping) URI(java.net.URI) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) SpringExtension(org.springframework.test.context.junit.jupiter.SpringExtension) ServerRequestCache(org.springframework.security.web.server.savedrequest.ServerRequestCache) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) SecurityTestExecutionListeners(org.springframework.security.test.context.annotation.SecurityTestExecutionListeners) Mono(reactor.core.publisher.Mono) ApplicationContext(org.springframework.context.ApplicationContext) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) RestController(org.springframework.web.bind.annotation.RestController) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Configuration(org.springframework.context.annotation.Configuration) InMemoryReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) WithMockUser(org.springframework.security.test.context.support.WithMockUser) SpringTestContext(org.springframework.security.config.test.SpringTestContext) TestOAuth2AuthorizationResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses) SpringTestContextExtension(org.springframework.security.config.test.SpringTestContextExtension) Bean(org.springframework.context.annotation.Bean) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) Mockito.mock(org.mockito.Mockito.mock) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) ServerRequestCache(org.springframework.security.web.server.savedrequest.ServerRequestCache) Test(org.junit.jupiter.api.Test)

Example 13 with ReactiveAuthenticationManager

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

the class OAuth2ClientSpecTests method oauth2ClientWhenCustomObjectsInLambdaThenUsed.

@Test
public void oauth2ClientWhenCustomObjectsInLambdaThenUsed() {
    this.spring.register(ClientRegistrationConfig.class, OAuth2ClientInLambdaCustomConfig.class, AuthorizedClientController.class).autowire();
    OAuth2ClientInLambdaCustomConfig config = this.spring.getContext().getBean(OAuth2ClientInLambdaCustomConfig.class);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    ReactiveAuthenticationManager manager = config.manager;
    ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> authorizationRequestRepository = config.authorizationRequestRepository;
    ServerRequestCache requestCache = config.requestCache;
    OAuth2AuthorizationRequest authorizationRequest = TestOAuth2AuthorizationRequests.request().redirectUri("/authorize/oauth2/code/registration-id").build();
    OAuth2AuthorizationResponse authorizationResponse = TestOAuth2AuthorizationResponses.success().redirectUri("/authorize/oauth2/code/registration-id").build();
    OAuth2AuthorizationExchange authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse);
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
    OAuth2AuthorizationCodeAuthenticationToken result = new OAuth2AuthorizationCodeAuthenticationToken(this.registration, authorizationExchange, accessToken);
    given(authorizationRequestRepository.loadAuthorizationRequest(any())).willReturn(Mono.just(authorizationRequest));
    given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
    given(manager.authenticate(any())).willReturn(Mono.just(result));
    given(requestCache.getRedirectUri(any())).willReturn(Mono.just(URI.create("/saved-request")));
    // @formatter:off
    this.client.get().uri((uriBuilder) -> uriBuilder.path("/authorize/oauth2/code/registration-id").queryParam(OAuth2ParameterNames.CODE, "code").queryParam(OAuth2ParameterNames.STATE, "state").build()).exchange().expectStatus().is3xxRedirection();
    // @formatter:on
    verify(converter).convert(any());
    verify(manager).authenticate(any());
    verify(requestCache).getRedirectUri(any());
}
Also used : ServerAuthorizationRequestRepository(org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) OAuth2ParameterNames(org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) TestOAuth2AccessTokens(org.springframework.security.oauth2.core.TestOAuth2AccessTokens) RegisteredOAuth2AuthorizedClient(org.springframework.security.oauth2.client.annotation.RegisteredOAuth2AuthorizedClient) TestOAuth2AuthorizationRequests(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests) Autowired(org.springframework.beans.factory.annotation.Autowired) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) EnableWebFlux(org.springframework.web.reactive.config.EnableWebFlux) EnableWebFluxSecurity(org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity) BDDMockito.given(org.mockito.BDDMockito.given) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) GetMapping(org.springframework.web.bind.annotation.GetMapping) URI(java.net.URI) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) ReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository) SpringExtension(org.springframework.test.context.junit.jupiter.SpringExtension) ServerRequestCache(org.springframework.security.web.server.savedrequest.ServerRequestCache) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) SecurityTestExecutionListeners(org.springframework.security.test.context.annotation.SecurityTestExecutionListeners) Mono(reactor.core.publisher.Mono) ApplicationContext(org.springframework.context.ApplicationContext) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) RestController(org.springframework.web.bind.annotation.RestController) OAuth2AuthorizedClient(org.springframework.security.oauth2.client.OAuth2AuthorizedClient) Mockito.verify(org.mockito.Mockito.verify) Test(org.junit.jupiter.api.Test) Configuration(org.springframework.context.annotation.Configuration) InMemoryReactiveClientRegistrationRepository(org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository) SecurityWebFilterChain(org.springframework.security.web.server.SecurityWebFilterChain) WithMockUser(org.springframework.security.test.context.support.WithMockUser) SpringTestContext(org.springframework.security.config.test.SpringTestContext) TestOAuth2AuthorizationResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses) SpringTestContextExtension(org.springframework.security.config.test.SpringTestContextExtension) Bean(org.springframework.context.annotation.Bean) ServerOAuth2AuthorizedClientRepository(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizedClientRepository) Mockito.mock(org.mockito.Mockito.mock) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) ServerRequestCache(org.springframework.security.web.server.savedrequest.ServerRequestCache) Test(org.junit.jupiter.api.Test)

Example 14 with ReactiveAuthenticationManager

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

the class OAuth2ResourceServerSpecTests method getWhenUsingCustomAuthenticationManagerResolverThenUsesItAccordingly.

@Test
public void getWhenUsingCustomAuthenticationManagerResolverThenUsesItAccordingly() {
    this.spring.register(CustomAuthenticationManagerResolverConfig.class).autowire();
    ReactiveAuthenticationManagerResolver<ServerWebExchange> authenticationManagerResolver = this.spring.getContext().getBean(ReactiveAuthenticationManagerResolver.class);
    ReactiveAuthenticationManager authenticationManager = this.spring.getContext().getBean(ReactiveAuthenticationManager.class);
    given(authenticationManagerResolver.resolve(any(ServerWebExchange.class))).willReturn(Mono.just(authenticationManager));
    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) ServerWebExchange(org.springframework.web.server.ServerWebExchange) 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 15 with ReactiveAuthenticationManager

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

the class OAuth2ResourceServerSpecTests method getWhenUsingCustomAuthenticationManagerThenUsesItAccordingly.

@Test
public void getWhenUsingCustomAuthenticationManagerThenUsesItAccordingly() {
    this.spring.register(CustomAuthenticationManagerConfig.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)

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