Search in sources :

Example 6 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project spring-security by spring-projects.

the class OAuth2LoginTests method oauth2LoginWhenCustomObjectsInLambdaThenUsed.

@Test
public void oauth2LoginWhenCustomObjectsInLambdaThenUsed() {
    this.spring.register(OAuth2LoginWithSingleClientRegistrations.class, OAuth2LoginMockAuthenticationManagerInLambdaConfig.class).autowire();
    String redirectLocation = "/custom-redirect-location";
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(this.springSecurity).build();
    OAuth2LoginMockAuthenticationManagerInLambdaConfig config = this.spring.getContext().getBean(OAuth2LoginMockAuthenticationManagerInLambdaConfig.class);
    ServerAuthenticationConverter converter = config.authenticationConverter;
    ReactiveAuthenticationManager manager = config.manager;
    ServerWebExchangeMatcher matcher = config.matcher;
    ServerOAuth2AuthorizationRequestResolver resolver = config.resolver;
    ServerAuthenticationSuccessHandler successHandler = config.successHandler;
    OAuth2AuthorizationExchange exchange = TestOAuth2AuthorizationExchanges.success();
    OAuth2User user = TestOAuth2Users.create();
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
    OAuth2LoginAuthenticationToken result = new OAuth2LoginAuthenticationToken(github, exchange, user, user.getAuthorities(), accessToken);
    given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
    given(manager.authenticate(any())).willReturn(Mono.just(result));
    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);
    });
    // @formatter:off
    webTestClient.get().uri("/login/oauth2/code/github").exchange().expectStatus().is3xxRedirection().expectHeader().valueEquals("Location", redirectLocation);
    // @formatter:on
    verify(converter).convert(any());
    verify(manager).authenticate(any());
    verify(matcher).matches(any());
    verify(resolver).resolve(any());
    verify(successHandler).onAuthenticationSuccess(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) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) ServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) Mono(reactor.core.publisher.Mono) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) WebFilterExchange(org.springframework.security.web.server.WebFilterExchange) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) ServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher) ServerOAuth2AuthorizationRequestResolver(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizationRequestResolver) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) Test(org.junit.jupiter.api.Test)

Example 7 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project spring-security by spring-projects.

the class OAuth2LoginTests method oauth2LoginWhenCustomObjectsThenUsed.

@Test
public void oauth2LoginWhenCustomObjectsThenUsed() {
    this.spring.register(OAuth2LoginWithSingleClientRegistrations.class, OAuth2LoginMockAuthenticationManagerConfig.class).autowire();
    String redirectLocation = "/custom-redirect-location";
    WebTestClient webTestClient = WebTestClientBuilder.bindToWebFilters(this.springSecurity).build();
    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;
    OAuth2AuthorizationExchange exchange = TestOAuth2AuthorizationExchanges.success();
    OAuth2User user = TestOAuth2Users.create();
    OAuth2AccessToken accessToken = TestOAuth2AccessTokens.noScopes();
    OAuth2LoginAuthenticationToken result = new OAuth2LoginAuthenticationToken(github, exchange, user, user.getAuthorities(), accessToken);
    given(converter.convert(any())).willReturn(Mono.just(new TestingAuthenticationToken("a", "b", "c")));
    given(manager.authenticate(any())).willReturn(Mono.just(result));
    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);
    });
    // @formatter:off
    webTestClient.get().uri("/login/oauth2/code/github").exchange().expectStatus().is3xxRedirection().expectHeader().valueEquals("Location", redirectLocation);
    // @formatter:on
    verify(converter).convert(any());
    verify(manager).authenticate(any());
    verify(matcher).matches(any());
    verify(resolver).resolve(any());
    verify(successHandler).onAuthenticationSuccess(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) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) WebTestClient(org.springframework.test.web.reactive.server.WebTestClient) ServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) Mono(reactor.core.publisher.Mono) ServerAuthenticationConverter(org.springframework.security.web.server.authentication.ServerAuthenticationConverter) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) WebFilterExchange(org.springframework.security.web.server.WebFilterExchange) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) Authentication(org.springframework.security.core.Authentication) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) ServerWebExchangeMatcher(org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher) ServerOAuth2AuthorizationRequestResolver(org.springframework.security.oauth2.client.web.server.ServerOAuth2AuthorizationRequestResolver) RedirectServerAuthenticationSuccessHandler(org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler) Test(org.junit.jupiter.api.Test)

Example 8 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project spring-security by spring-projects.

the class OidcAuthorizationCodeAuthenticationProviderTests method authenticateWhenJwkSetUriNotSetThenThrowOAuth2AuthenticationException.

@Test
public void authenticateWhenJwkSetUriNotSetThenThrowOAuth2AuthenticationException() {
    // @formatter:off
    ClientRegistration clientRegistration = TestClientRegistrations.clientRegistration().jwkSetUri(null).build();
    // @formatter:on
    assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(clientRegistration, this.authorizationExchange))).withMessageContaining("missing_signature_verifier");
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) Test(org.junit.jupiter.api.Test)

Example 9 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project spring-security by spring-projects.

the class OidcAuthorizationCodeAuthenticationProviderTests method authenticateWhenLoginSuccessThenReturnAuthentication.

@Test
public void authenticateWhenLoginSuccessThenReturnAuthentication() {
    Map<String, Object> claims = new HashMap<>();
    claims.put(IdTokenClaimNames.ISS, "https://provider.com");
    claims.put(IdTokenClaimNames.SUB, "subject1");
    claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
    claims.put(IdTokenClaimNames.AZP, "client1");
    claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
    this.setUpIdToken(claims);
    OidcUser principal = mock(OidcUser.class);
    List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
    given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
    given(this.userService.loadUser(any())).willReturn(principal);
    OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
    assertThat(authentication.isAuthenticated()).isTrue();
    assertThat(authentication.getPrincipal()).isEqualTo(principal);
    assertThat(authentication.getCredentials()).isEqualTo("");
    assertThat(authentication.getAuthorities()).isEqualTo(authorities);
    assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration);
    assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange);
    assertThat(authentication.getAccessToken()).isEqualTo(this.accessTokenResponse.getAccessToken());
    assertThat(authentication.getRefreshToken()).isEqualTo(this.accessTokenResponse.getRefreshToken());
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Jwt(org.springframework.security.oauth2.jwt.Jwt) StringKeyGenerator(org.springframework.security.crypto.keygen.StringKeyGenerator) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Set(java.util.Set) TestJwts(org.springframework.security.oauth2.jwt.TestJwts) Instant(java.time.Instant) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) Base64(java.util.Base64) List(java.util.List) Base64StringKeyGenerator(org.springframework.security.crypto.keygen.Base64StringKeyGenerator) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) 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) Answer(org.mockito.stubbing.Answer) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) LinkedHashSet(java.util.LinkedHashSet) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OAuth2UserService(org.springframework.security.oauth2.client.userinfo.OAuth2UserService) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) TestOAuth2AuthorizationResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) JwtException(org.springframework.security.oauth2.jwt.JwtException) Collections(java.util.Collections) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) HashMap(java.util.HashMap) GrantedAuthority(org.springframework.security.core.GrantedAuthority) List(java.util.List) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) Test(org.junit.jupiter.api.Test)

Example 10 with OAuth2LoginAuthenticationToken

use of org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken in project spring-security by spring-projects.

the class OidcAuthorizationCodeAuthenticationProviderTests method authenticateWhenIdTokenInvalidNonceThenThrowOAuth2AuthenticationException.

@Test
public void authenticateWhenIdTokenInvalidNonceThenThrowOAuth2AuthenticationException() {
    Map<String, Object> claims = new HashMap<>();
    claims.put(IdTokenClaimNames.ISS, "https://provider.com");
    claims.put(IdTokenClaimNames.SUB, "subject1");
    claims.put(IdTokenClaimNames.AUD, Arrays.asList("client1", "client2"));
    claims.put(IdTokenClaimNames.AZP, "client1");
    claims.put(IdTokenClaimNames.NONCE, "invalid-nonce-hash");
    this.setUpIdToken(claims);
    assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange))).withMessageContaining("[invalid_nonce]");
}
Also used : HashMap(java.util.HashMap) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) Test(org.junit.jupiter.api.Test)

Aggregations

OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)29 Test (org.junit.jupiter.api.Test)25 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)23 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)21 OAuth2AuthorizationExchange (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange)20 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)16 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)15 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)15 Authentication (org.springframework.security.core.Authentication)13 HashMap (java.util.HashMap)12 Map (java.util.Map)12 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)12 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)11 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)11 BDDMockito.given (org.mockito.BDDMockito.given)11 Mockito.mock (org.mockito.Mockito.mock)11 Answer (org.mockito.stubbing.Answer)11 AuthorityUtils (org.springframework.security.core.authority.AuthorityUtils)11 TestClientRegistrations (org.springframework.security.oauth2.client.registration.TestClientRegistrations)11