@Test public void constructorTokenRequestResponseWhenAllParametersProvidedAndValidThenCreated() { OAuth2LoginAuthenticationToken authentication = new OAuth2LoginAuthenticationToken( this.clientRegistration, this.authorizationExchange, this.principal, this.authorities, this.accessToken); assertThat(authentication.getPrincipal()).isEqualTo(this.principal); assertThat(authentication.getCredentials()).isEqualTo(""); assertThat(authentication.getAuthorities()).isEqualTo(this.authorities); assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange); assertThat(authentication.getAccessToken()).isEqualTo(this.accessToken); assertThat(authentication.isAuthenticated()).isEqualTo(true); } }
private void setUpAuthenticationResult(ClientRegistration registration) { OAuth2User user = mock(OAuth2User.class); when(user.getName()).thenReturn(this.principalName1); this.loginAuthentication = mock(OAuth2LoginAuthenticationToken.class); when(this.loginAuthentication.getPrincipal()).thenReturn(user); when(this.loginAuthentication.getName()).thenReturn(this.principalName1); when(this.loginAuthentication.getAuthorities()).thenReturn(AuthorityUtils.createAuthorityList("ROLE_USER")); when(this.loginAuthentication.getClientRegistration()).thenReturn(registration); when(this.loginAuthentication.getAuthorizationExchange()).thenReturn(success()); when(this.loginAuthentication.getAccessToken()).thenReturn(mock(OAuth2AccessToken.class)); when(this.loginAuthentication.getRefreshToken()).thenReturn(mock(OAuth2RefreshToken.class)); when(this.loginAuthentication.isAuthenticated()).thenReturn(true); when(this.authenticationManager.authenticate(any(Authentication.class))).thenReturn(this.loginAuthentication); } }
if (authorizationCodeAuthentication.getAuthorizationExchange() .getAuthorizationRequest().getScopes().contains("openid")) { try { OAuth2AuthorizationExchangeValidator.validate( authorizationCodeAuthentication.getAuthorizationExchange()); authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange())); authorizationCodeAuthentication.getClientRegistration(), accessToken, additionalParameters)); OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken( authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), oauth2User, mappedAuthorities, accessToken, accessTokenResponse.getRefreshToken()); authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
@Override protected Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) { OAuth2LoginAuthenticationToken authenticationResult = (OAuth2LoginAuthenticationToken) authentication; OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient( authenticationResult.getClientRegistration(), authenticationResult.getName(), authenticationResult.getAccessToken(), authenticationResult.getRefreshToken()); OAuth2AuthenticationToken result = new OAuth2AuthenticationToken( authenticationResult.getPrincipal(), authenticationResult.getAuthorities(), authenticationResult.getClientRegistration().getRegistrationId()); return this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authenticationResult, webFilterExchange.getExchange()) .then(super.onAuthenticationSuccess(result, webFilterExchange)); } }
OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params, redirectUri); OAuth2LoginAuthenticationToken authenticationRequest = new OAuth2LoginAuthenticationToken( clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse)); authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); authenticationResult.getPrincipal(), authenticationResult.getAuthorities(), authenticationResult.getClientRegistration().getRegistrationId()); authenticationResult.getClientRegistration(), oauth2Authentication.getName(), authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
@Test(expected = IllegalArgumentException.class) public void constructorTokenRequestResponseWhenPrincipalIsNullThenThrowIllegalArgumentException() { new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange, null, this.authorities, this.accessToken); }
@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { OAuth2LoginAuthenticationToken authorizationCodeAuthentication = (OAuth2LoginAuthenticationToken) authentication; // Section 3.1.2.1 Authentication Request - http://openid.net/specs/openid-connect-core-1_0.html#AuthRequest // scope // REQUIRED. OpenID Connect requests MUST contain the "openid" scope value. if (authorizationCodeAuthentication.getAuthorizationExchange() .getAuthorizationRequest().getScopes().contains(OidcScopes.OPENID)) { OAuth2Error oauth2Error = new OAuth2Error( "oidc_provider_not_configured", "An OpenID Connect Authentication Provider has not been configured. " + "Check to ensure you include the dependency 'spring-security-oauth2-jose'.", null); throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString()); } return null; }
@Test public void authenticationWhenRefreshTokenThenRefreshTokenInAuthorizedClient() { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo") .tokenType(OAuth2AccessToken.TokenType.BEARER) .additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue())) .refreshToken("refresh-token") .build(); Map<String, Object> claims = new HashMap<>(); claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com"); claims.put(IdTokenClaimNames.SUB, "rob"); claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id")); Instant issuedAt = Instant.now(); Instant expiresAt = Instant.from(issuedAt).plusSeconds(3600); Jwt idToken = new Jwt("id-token", issuedAt, expiresAt, claims, claims); when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken); when(this.userService.loadUser(any())).thenReturn(Mono.just(user)); when(this.jwtDecoder.decode(any())).thenReturn(Mono.just(idToken)); this.manager.setJwtDecoderFactory(c -> this.jwtDecoder); OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken()).block(); assertThat(result.getPrincipal()).isEqualTo(user); assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities()); assertThat(result.isAuthenticated()).isTrue(); assertThat(result.getRefreshToken().getTokenValue()).isNotNull(); }
@Test public void authenticationWhenOAuth2UserFoundThenSuccess() { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo") .tokenType(OAuth2AccessToken.TokenType.BEARER) .build(); when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); DefaultOAuth2User user = new DefaultOAuth2User(AuthorityUtils.createAuthorityList("ROLE_USER"), Collections.singletonMap("user", "rob"), "user"); when(this.userService.loadUser(any())).thenReturn(Mono.just(user)); OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken()).block(); assertThat(result.getPrincipal()).isEqualTo(user); assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities()); assertThat(result.isAuthenticated()).isTrue(); }
@Test public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() { 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"); this.setUpIdToken(claims); OidcUser principal = mock(OidcUser.class); List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); when(principal.getAuthorities()).thenAnswer( (Answer<List<GrantedAuthority>>) invocation -> authorities); when(this.userService.loadUser(any())).thenReturn(principal); List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER"); GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class); when(authoritiesMapper.mapAuthorities(anyCollection())).thenAnswer( (Answer<List<GrantedAuthority>>) invocation -> mappedAuthorities); this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper); OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate( new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)); assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities); }
OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponseUtils.convert(params, redirectUri); OAuth2LoginAuthenticationToken authenticationRequest = new OAuth2LoginAuthenticationToken( clientRegistration, new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse)); authenticationRequest.setDetails(this.authenticationDetailsSource.buildDetails(request)); authenticationResult.getPrincipal(), authenticationResult.getAuthorities(), authenticationResult.getClientRegistration().getRegistrationId()); authenticationResult.getClientRegistration(), oauth2Authentication.getName(), authenticationResult.getAccessToken(), authenticationResult.getRefreshToken());
@Override protected Mono<Void> onAuthenticationSuccess(Authentication authentication, WebFilterExchange webFilterExchange) { OAuth2LoginAuthenticationToken authenticationResult = (OAuth2LoginAuthenticationToken) authentication; OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient( authenticationResult.getClientRegistration(), authenticationResult.getName(), authenticationResult.getAccessToken(), authenticationResult.getRefreshToken()); OAuth2AuthenticationToken result = new OAuth2AuthenticationToken( authenticationResult.getPrincipal(), authenticationResult.getAuthorities(), authenticationResult.getClientRegistration().getRegistrationId()); return this.authorizedClientRepository.saveAuthorizedClient(authorizedClient, authenticationResult, webFilterExchange.getExchange()) .then(super.onAuthenticationSuccess(result, webFilterExchange)); } }
@Test(expected = IllegalArgumentException.class) public void constructorTokenRequestResponseWhenAuthorizationExchangeIsNullThenThrowIllegalArgumentException() { new OAuth2LoginAuthenticationToken(this.clientRegistration, null, this.principal, this.authorities, this.accessToken); }
@Test public void doFilterWhenAuthorizationResponseHasDefaultPort80ThenRedirectUriMatchingExcludesPort() throws Exception { String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId(); String state = "state"; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); request.setScheme("http"); request.setServerName("example.com"); request.setServerPort(80); request.setServletPath(requestUri); request.addParameter(OAuth2ParameterNames.CODE, "code"); request.addParameter(OAuth2ParameterNames.STATE, "state"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.setUpAuthorizationRequest(request, response, this.registration2, state); this.setUpAuthenticationResult(this.registration2); this.filter.doFilter(request, response, filterChain); ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class); verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture()); OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor.getValue(); OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange().getAuthorizationRequest(); OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange().getAuthorizationResponse(); String expectedRedirectUri = "http://example.com/login/oauth2/code/registration-id-2"; assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri); assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri); }
@Test public void authenticationWhenOAuth2UserFoundThenSuccess() { OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo") .tokenType(OAuth2AccessToken.TokenType.BEARER) .additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue())) .build(); Map<String, Object> claims = new HashMap<>(); claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com"); claims.put(IdTokenClaimNames.SUB, "rob"); claims.put(IdTokenClaimNames.AUD, Arrays.asList("client-id")); Instant issuedAt = Instant.now(); Instant expiresAt = Instant.from(issuedAt).plusSeconds(3600); Jwt idToken = new Jwt("id-token", issuedAt, expiresAt, claims, claims); when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(Mono.just(accessTokenResponse)); DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken); when(this.userService.loadUser(any())).thenReturn(Mono.just(user)); when(this.jwtDecoder.decode(any())).thenReturn(Mono.just(idToken)); this.manager.setJwtDecoderFactory(c -> this.jwtDecoder); OAuth2LoginAuthenticationToken result = (OAuth2LoginAuthenticationToken) this.manager.authenticate(loginToken()).block(); assertThat(result.getPrincipal()).isEqualTo(user); assertThat(result.getAuthorities()).containsOnlyElementsOf(user.getAuthorities()); assertThat(result.isAuthenticated()).isTrue(); }
@Test public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() { OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse(); when(this.accessTokenResponseClient.getTokenResponse(any())).thenReturn(accessTokenResponse); OAuth2User principal = mock(OAuth2User.class); List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER"); when(principal.getAuthorities()).thenAnswer( (Answer<List<GrantedAuthority>>) invocation -> authorities); when(this.userService.loadUser(any())).thenReturn(principal); List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OAUTH2_USER"); GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class); when(authoritiesMapper.mapAuthorities(anyCollection())).thenAnswer( (Answer<List<GrantedAuthority>>) invocation -> mappedAuthorities); this.authenticationProvider.setAuthoritiesMapper(authoritiesMapper); OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) this.authenticationProvider.authenticate( new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange)); assertThat(authentication.getAuthorities()).isEqualTo(mappedAuthorities); }
@Test public void constructorAuthorizationRequestResponseWhenAllParametersProvidedAndValidThenCreated() { OAuth2LoginAuthenticationToken authentication = new OAuth2LoginAuthenticationToken( this.clientRegistration, this.authorizationExchange); assertThat(authentication.getPrincipal()).isNull(); assertThat(authentication.getCredentials()).isEqualTo(""); assertThat(authentication.getAuthorities()).isEqualTo(Collections.emptyList()); assertThat(authentication.getClientRegistration()).isEqualTo(this.clientRegistration); assertThat(authentication.getAuthorizationExchange()).isEqualTo(this.authorizationExchange); assertThat(authentication.getAccessToken()).isNull(); assertThat(authentication.isAuthenticated()).isEqualTo(false); }
if (!authorizationCodeAuthentication.getAuthorizationExchange() .getAuthorizationRequest().getScopes().contains(OidcScopes.OPENID)) { .getAuthorizationExchange().getAuthorizationRequest(); OAuth2AuthorizationResponse authorizationResponse = authorizationCodeAuthentication .getAuthorizationExchange().getAuthorizationResponse(); accessTokenResponse = this.accessTokenResponseClient.getTokenResponse( new OAuth2AuthorizationCodeGrantRequest( authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange())); } catch (OAuth2AuthorizationException ex) { OAuth2Error oauth2Error = ex.getError(); ClientRegistration clientRegistration = authorizationCodeAuthentication.getClientRegistration(); this.authoritiesMapper.mapAuthorities(oidcUser.getAuthorities()); OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken( authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), oidcUser, mappedAuthorities, accessTokenResponse.getAccessToken(), accessTokenResponse.getRefreshToken()); authenticationResult.setDetails(authorizationCodeAuthentication.getDetails());
@Test public void constructorTokenRequestResponseWhenAuthoritiesIsEmptyThenCreated() { new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange, this.principal, Collections.emptyList(), this.accessToken); }
@Test public void doFilterWhenAuthorizationResponseHasDefaultPort443ThenRedirectUriMatchingExcludesPort() throws Exception { String requestUri = "/login/oauth2/code/" + this.registration2.getRegistrationId(); String state = "state"; MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); request.setScheme("https"); request.setServerName("example.com"); request.setServerPort(443); request.setServletPath(requestUri); request.addParameter(OAuth2ParameterNames.CODE, "code"); request.addParameter(OAuth2ParameterNames.STATE, "state"); MockHttpServletResponse response = new MockHttpServletResponse(); FilterChain filterChain = mock(FilterChain.class); this.setUpAuthorizationRequest(request, response, this.registration2, state); this.setUpAuthenticationResult(this.registration2); this.filter.doFilter(request, response, filterChain); ArgumentCaptor<Authentication> authenticationArgCaptor = ArgumentCaptor.forClass(Authentication.class); verify(this.authenticationManager).authenticate(authenticationArgCaptor.capture()); OAuth2LoginAuthenticationToken authentication = (OAuth2LoginAuthenticationToken) authenticationArgCaptor.getValue(); OAuth2AuthorizationRequest authorizationRequest = authentication.getAuthorizationExchange().getAuthorizationRequest(); OAuth2AuthorizationResponse authorizationResponse = authentication.getAuthorizationExchange().getAuthorizationResponse(); String expectedRedirectUri = "https://example.com/login/oauth2/code/registration-id-2"; assertThat(authorizationRequest.getRedirectUri()).isEqualTo(expectedRedirectUri); assertThat(authorizationResponse.getRedirectUri()).isEqualTo(expectedRedirectUri); }