Search in sources :

Example 26 with OidcUserRequest

use of org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest in project spring-security by spring-projects.

the class OidcUserServiceTests method loadUserWhenCustomClaimTypeConverterFactorySetThenApplied.

@Test
public void loadUserWhenCustomClaimTypeConverterFactorySetThenApplied() {
    // @formatter:off
    String userInfoResponse = "{\n" + "   \"sub\": \"subject1\",\n" + "   \"name\": \"first last\",\n" + "   \"given_name\": \"first\",\n" + "   \"family_name\": \"last\",\n" + "   \"preferred_username\": \"user1\",\n" + "   \"email\": \"user1@example.com\"\n" + "}\n";
    // @formatter:on
    this.server.enqueue(jsonResponse(userInfoResponse));
    String userInfoUri = this.server.url("/user").toString();
    ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
    Function<ClientRegistration, Converter<Map<String, Object>, Map<String, Object>>> customClaimTypeConverterFactory = mock(Function.class);
    this.userService.setClaimTypeConverterFactory(customClaimTypeConverterFactory);
    given(customClaimTypeConverterFactory.apply(same(clientRegistration))).willReturn(new ClaimTypeConverter(OidcUserService.createDefaultClaimTypeConverters()));
    this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken));
    verify(customClaimTypeConverterFactory).apply(same(clientRegistration));
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) ClaimTypeConverter(org.springframework.security.oauth2.core.converter.ClaimTypeConverter) Converter(org.springframework.core.convert.converter.Converter) ClaimTypeConverter(org.springframework.security.oauth2.core.converter.ClaimTypeConverter) Test(org.junit.jupiter.api.Test)

Example 27 with OidcUserRequest

use of org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest in project spring-security by spring-projects.

the class OidcUserServiceTests method loadUserWhenUserInfoUriInvalidThenThrowOAuth2AuthenticationException.

@Test
public void loadUserWhenUserInfoUriInvalidThenThrowOAuth2AuthenticationException() {
    String userInfoUri = "https://invalid-provider.com/user";
    ClientRegistration clientRegistration = this.clientRegistrationBuilder.userInfoUri(userInfoUri).build();
    assertThatExceptionOfType(OAuth2AuthenticationException.class).isThrownBy(() -> this.userService.loadUser(new OidcUserRequest(clientRegistration, this.accessToken, this.idToken))).withMessageContaining("[invalid_user_info_response] An error occurred while attempting to retrieve the UserInfo Resource");
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Test(org.junit.jupiter.api.Test)

Example 28 with OidcUserRequest

use of org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest in project spring-security by spring-projects.

the class OidcAuthorizationCodeReactiveAuthenticationManager method authenticationResult.

private Mono<OAuth2LoginAuthenticationToken> authenticationResult(OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication, OAuth2AccessTokenResponse accessTokenResponse) {
    OAuth2AccessToken accessToken = accessTokenResponse.getAccessToken();
    ClientRegistration clientRegistration = authorizationCodeAuthentication.getClientRegistration();
    Map<String, Object> additionalParameters = accessTokenResponse.getAdditionalParameters();
    if (!additionalParameters.containsKey(OidcParameterNames.ID_TOKEN)) {
        OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, "Missing (required) ID Token in Token Response for Client Registration: " + clientRegistration.getRegistrationId(), null);
        return Mono.error(new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString()));
    }
    // @formatter:off
    return createOidcToken(clientRegistration, accessTokenResponse).doOnNext((idToken) -> validateNonce(authorizationCodeAuthentication, idToken)).map((idToken) -> new OidcUserRequest(clientRegistration, accessToken, idToken, additionalParameters)).flatMap(this.userService::loadUser).map((oauth2User) -> {
        Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper.mapAuthorities(oauth2User.getAuthorities());
        return new OAuth2LoginAuthenticationToken(authorizationCodeAuthentication.getClientRegistration(), authorizationCodeAuthentication.getAuthorizationExchange(), oauth2User, mappedAuthorities, accessToken, accessTokenResponse.getRefreshToken());
    });
// @formatter:on
}
Also used : OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) MessageDigest(java.security.MessageDigest) OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) OidcParameterNames(org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) Map(java.util.Map) ReactiveAuthenticationManager(org.springframework.security.authentication.ReactiveAuthenticationManager) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) Collection(java.util.Collection) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) ReactiveOAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.ReactiveOAuth2AccessTokenResponseClient) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) StandardCharsets(java.nio.charset.StandardCharsets) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) Base64(java.util.Base64) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) ReactiveJwtDecoderFactory(org.springframework.security.oauth2.jwt.ReactiveJwtDecoderFactory) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) JwtException(org.springframework.security.oauth2.jwt.JwtException) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Assert(org.springframework.util.Assert) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)

Example 29 with OidcUserRequest

use of org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest in project spring-security by spring-projects.

the class OidcAuthorizationCodeReactiveAuthenticationManagerTests method authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities.

@Test
public void authenticateWhenAuthoritiesMapperSetThenReturnMappedAuthorities() {
    ClientRegistration clientRegistration = this.registration.build();
    // @formatter:off
    OAuth2AccessTokenResponse accessTokenResponse = OAuth2AccessTokenResponse.withToken("foo").tokenType(OAuth2AccessToken.TokenType.BEARER).additionalParameters(Collections.singletonMap(OidcParameterNames.ID_TOKEN, this.idToken.getTokenValue())).build();
    // @formatter:on
    OAuth2AuthorizationCodeAuthenticationToken authorizationCodeAuthentication = loginToken();
    Map<String, Object> claims = new HashMap<>();
    claims.put(IdTokenClaimNames.ISS, "https://issuer.example.com");
    claims.put(IdTokenClaimNames.SUB, "rob");
    claims.put(IdTokenClaimNames.AUD, Collections.singletonList(clientRegistration.getClientId()));
    claims.put(IdTokenClaimNames.NONCE, this.nonceHash);
    Jwt idToken = TestJwts.jwt().claims((c) -> c.putAll(claims)).build();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(Mono.just(accessTokenResponse));
    DefaultOidcUser user = new DefaultOidcUser(AuthorityUtils.createAuthorityList("ROLE_USER"), this.idToken);
    ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
    given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(Mono.just(user));
    List<GrantedAuthority> mappedAuthorities = AuthorityUtils.createAuthorityList("ROLE_OIDC_USER");
    GrantedAuthoritiesMapper authoritiesMapper = mock(GrantedAuthoritiesMapper.class);
    given(authoritiesMapper.mapAuthorities(anyCollection())).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> mappedAuthorities);
    given(this.jwtDecoder.decode(any())).willReturn(Mono.just(idToken));
    this.manager.setJwtDecoderFactory((c) -> this.jwtDecoder);
    this.manager.setAuthoritiesMapper(authoritiesMapper);
    Authentication result = this.manager.authenticate(authorizationCodeAuthentication).block();
    assertThat(result.getAuthorities()).isEqualTo(mappedAuthorities);
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) OidcUser(org.springframework.security.oauth2.core.oidc.user.OidcUser) TestingAuthenticationToken(org.springframework.security.authentication.TestingAuthenticationToken) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Jwt(org.springframework.security.oauth2.jwt.Jwt) ReactiveJwtDecoder(org.springframework.security.oauth2.jwt.ReactiveJwtDecoder) StringKeyGenerator(org.springframework.security.crypto.keygen.StringKeyGenerator) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) 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) 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) Authentication(org.springframework.security.core.Authentication) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Mock(org.mockito.Mock) IdTokenClaimNames(org.springframework.security.oauth2.core.oidc.IdTokenClaimNames) 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) ReactiveOAuth2UserService(org.springframework.security.oauth2.client.userinfo.ReactiveOAuth2UserService) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) OAuth2LoginAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OidcIdToken(org.springframework.security.oauth2.core.oidc.OidcIdToken) TestOidcIdTokens(org.springframework.security.oauth2.core.oidc.TestOidcIdTokens) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Mono(reactor.core.publisher.Mono) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) 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) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) HashMap(java.util.HashMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2AuthorizationCodeAuthenticationToken(org.springframework.security.oauth2.client.authentication.OAuth2AuthorizationCodeAuthenticationToken) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) Authentication(org.springframework.security.core.Authentication) List(java.util.List) DefaultOidcUser(org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser) Test(org.junit.jupiter.api.Test)

Example 30 with OidcUserRequest

use of org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest in project spring-security by spring-projects.

the class OidcAuthorizationCodeAuthenticationProviderTests method authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest.

// gh-5368
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
    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);
    ArgumentCaptor<OidcUserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OidcUserRequest.class);
    given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
    this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
    assertThat(userRequestArgCaptor.getValue().getAdditionalParameters()).containsAllEntriesOf(this.accessTokenResponse.getAdditionalParameters());
}
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) OidcUserRequest(org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest) 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)

Aggregations

Test (org.junit.jupiter.api.Test)25 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)23 OidcUser (org.springframework.security.oauth2.core.oidc.user.OidcUser)20 OidcUserRequest (org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest)8 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)7 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)7 GrantedAuthority (org.springframework.security.core.GrantedAuthority)6 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)6 OAuth2AuthorizationRequest (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest)6 OAuth2AuthorizationResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse)6 HashMap (java.util.HashMap)5 OAuth2LoginAuthenticationToken (org.springframework.security.oauth2.client.authentication.OAuth2LoginAuthenticationToken)5 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 Base64 (java.util.Base64)4 Map (java.util.Map)4 GrantedAuthoritiesMapper (org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper)4 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)4 Arrays (java.util.Arrays)3 Collections (java.util.Collections)3