Search in sources :

Example 21 with OAuth2UserRequest

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

the class OAuth2LoginAuthenticationProviderTests method authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest.

// gh-5368
@Test
public void authenticateWhenTokenSuccessResponseThenAdditionalParametersAddedToUserRequest() {
    OAuth2AccessTokenResponse accessTokenResponse = this.accessTokenSuccessResponse();
    given(this.accessTokenResponseClient.getTokenResponse(any())).willReturn(accessTokenResponse);
    OAuth2User principal = mock(OAuth2User.class);
    List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_USER");
    given(principal.getAuthorities()).willAnswer((Answer<List<GrantedAuthority>>) (invocation) -> authorities);
    ArgumentCaptor<OAuth2UserRequest> userRequestArgCaptor = ArgumentCaptor.forClass(OAuth2UserRequest.class);
    given(this.userService.loadUser(userRequestArgCaptor.capture())).willReturn(principal);
    this.authenticationProvider.authenticate(new OAuth2LoginAuthenticationToken(this.clientRegistration, this.authorizationExchange));
    assertThat(userRequestArgCaptor.getValue().getAdditionalParameters()).containsAllEntriesOf(accessTokenResponse.getAdditionalParameters());
}
Also used : OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TestOAuth2AuthorizationRequests(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationRequests) HashMap(java.util.HashMap) Answer(org.mockito.stubbing.Answer) ArgumentCaptor(org.mockito.ArgumentCaptor) BDDMockito.given(org.mockito.BDDMockito.given) Map(java.util.Map) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) LinkedHashSet(java.util.LinkedHashSet) TestClientRegistrations(org.springframework.security.oauth2.client.registration.TestClientRegistrations) OAuth2AuthorizationResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationResponse) OAuth2AuthorizationExchange(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationExchange) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Set(java.util.Set) Instant(java.time.Instant) OAuth2ErrorCodes(org.springframework.security.oauth2.core.OAuth2ErrorCodes) OAuth2AccessTokenResponse(org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) GrantedAuthority(org.springframework.security.core.GrantedAuthority) Test(org.junit.jupiter.api.Test) OAuth2AccessTokenResponseClient(org.springframework.security.oauth2.client.endpoint.OAuth2AccessTokenResponseClient) OAuth2AuthorizationCodeGrantRequest(org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest) ArgumentMatchers.anyCollection(org.mockito.ArgumentMatchers.anyCollection) List(java.util.List) GrantedAuthoritiesMapper(org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper) OAuth2UserService(org.springframework.security.oauth2.client.userinfo.OAuth2UserService) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) TestOAuth2AuthorizationResponses(org.springframework.security.oauth2.core.endpoint.TestOAuth2AuthorizationResponses) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) AuthorityUtils(org.springframework.security.core.authority.AuthorityUtils) Mockito.mock(org.mockito.Mockito.mock) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) GrantedAuthority(org.springframework.security.core.GrantedAuthority) List(java.util.List) OAuth2UserRequest(org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest) Test(org.junit.jupiter.api.Test)

Example 22 with OAuth2UserRequest

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

the class CustomUserTypesOAuth2UserService method loadUser.

@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
    Assert.notNull(userRequest, "userRequest cannot be null");
    String registrationId = userRequest.getClientRegistration().getRegistrationId();
    Class<? extends OAuth2User> customUserType = this.customUserTypes.get(registrationId);
    if (customUserType == null) {
        return null;
    }
    RequestEntity<?> request = this.requestEntityConverter.convert(userRequest);
    ResponseEntity<? extends OAuth2User> response = getResponse(customUserType, request);
    OAuth2User oauth2User = response.getBody();
    return oauth2User;
}
Also used : OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User)

Example 23 with OAuth2UserRequest

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

the class DefaultReactiveOAuth2UserService method loadUser.

@Override
public Mono<OAuth2User> loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
    return Mono.defer(() -> {
        Assert.notNull(userRequest, "userRequest cannot be null");
        String userInfoUri = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri();
        if (!StringUtils.hasText(userInfoUri)) {
            OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE, "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
        String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
        if (!StringUtils.hasText(userNameAttributeName)) {
            OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE, "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        }
        AuthenticationMethod authenticationMethod = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod();
        WebClient.RequestHeadersSpec<?> requestHeadersSpec = getRequestHeaderSpec(userRequest, userInfoUri, authenticationMethod);
        // @formatter:off
        Mono<Map<String, Object>> userAttributes = requestHeadersSpec.retrieve().onStatus(HttpStatus::isError, (response) -> parse(response).map((userInfoErrorResponse) -> {
            String description = userInfoErrorResponse.getErrorObject().getDescription();
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, description, null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
        })).bodyToMono(DefaultReactiveOAuth2UserService.STRING_OBJECT_MAP);
        return userAttributes.map((attrs) -> {
            GrantedAuthority authority = new OAuth2UserAuthority(attrs);
            Set<GrantedAuthority> authorities = new HashSet<>();
            authorities.add(authority);
            OAuth2AccessToken token = userRequest.getAccessToken();
            for (String scope : token.getScopes()) {
                authorities.add(new SimpleGrantedAuthority("SCOPE_" + scope));
            }
            return new DefaultOAuth2User(authorities, attrs, userNameAttributeName);
        }).onErrorMap((ex) -> (ex instanceof UnsupportedMediaTypeException || ex.getCause() instanceof UnsupportedMediaTypeException), (ex) -> {
            String contentType = (ex instanceof UnsupportedMediaTypeException) ? ((UnsupportedMediaTypeException) ex).getContentType().toString() : ((UnsupportedMediaTypeException) ex.getCause()).getContentType().toString();
            String errorMessage = "An error occurred while attempting to retrieve the UserInfo Resource from '" + userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri() + "': response contains invalid content type '" + contentType + "'. " + "The UserInfo Response should return a JSON object (content type 'application/json') " + "that contains a collection of name and value pairs of the claims about the authenticated End-User. " + "Please ensure the UserInfo Uri in UserInfoEndpoint for Client Registration '" + userRequest.getClientRegistration().getRegistrationId() + "' conforms to the UserInfo Endpoint, " + "as defined in OpenID Connect 1.0: 'https://openid.net/specs/openid-connect-core-1_0.html#UserInfo'";
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, errorMessage, null);
            throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
        }).onErrorMap((ex) -> {
            OAuth2Error oauth2Error = new OAuth2Error(INVALID_USER_INFO_RESPONSE_ERROR_CODE, "An error occurred reading the UserInfo response: " + ex.getMessage(), null);
            return new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString(), ex);
        });
    });
// @formatter:on
}
Also used : UnsupportedMediaTypeException(org.springframework.web.reactive.function.UnsupportedMediaTypeException) ParameterizedTypeReference(org.springframework.core.ParameterizedTypeReference) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) WebClient(org.springframework.web.reactive.function.client.WebClient) HashSet(java.util.HashSet) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) Map(java.util.Map) UserInfoErrorResponse(com.nimbusds.openid.connect.sdk.UserInfoErrorResponse) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) ClientResponse(org.springframework.web.reactive.function.client.ClientResponse) HttpHeaders(org.springframework.http.HttpHeaders) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) MediaType(org.springframework.http.MediaType) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Set(java.util.Set) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) Mono(reactor.core.publisher.Mono) GrantedAuthority(org.springframework.security.core.GrantedAuthority) HttpStatus(org.springframework.http.HttpStatus) AuthenticationMethod(org.springframework.security.oauth2.core.AuthenticationMethod) JSONObject(net.minidev.json.JSONObject) OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) AuthenticationMethod(org.springframework.security.oauth2.core.AuthenticationMethod) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) WebClient(org.springframework.web.reactive.function.client.WebClient) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) UnsupportedMediaTypeException(org.springframework.web.reactive.function.UnsupportedMediaTypeException) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Map(java.util.Map) HashSet(java.util.HashSet)

Example 24 with OAuth2UserRequest

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

the class DefaultOAuth2UserService method loadUser.

@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
    Assert.notNull(userRequest, "userRequest cannot be null");
    if (!StringUtils.hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) {
        OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE, "Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();
    if (!StringUtils.hasText(userNameAttributeName)) {
        OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE, "Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: " + userRequest.getClientRegistration().getRegistrationId(), null);
        throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
    }
    RequestEntity<?> request = this.requestEntityConverter.convert(userRequest);
    ResponseEntity<Map<String, Object>> response = getResponse(userRequest, request);
    Map<String, Object> userAttributes = response.getBody();
    Set<GrantedAuthority> authorities = new LinkedHashSet<>();
    authorities.add(new OAuth2UserAuthority(userAttributes));
    OAuth2AccessToken token = userRequest.getAccessToken();
    for (String authority : token.getScopes()) {
        authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
    }
    return new DefaultOAuth2User(authorities, userAttributes, userNameAttributeName);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) OAuth2AccessToken(org.springframework.security.oauth2.core.OAuth2AccessToken) DefaultOAuth2User(org.springframework.security.oauth2.core.user.DefaultOAuth2User) OAuth2AuthenticationException(org.springframework.security.oauth2.core.OAuth2AuthenticationException) Map(java.util.Map)

Example 25 with OAuth2UserRequest

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

the class OAuth2UserRequestEntityConverter method convert.

/**
 * Returns the {@link RequestEntity} used for the UserInfo Request.
 * @param userRequest the user request
 * @return the {@link RequestEntity} used for the UserInfo Request
 */
@Override
public RequestEntity<?> convert(OAuth2UserRequest userRequest) {
    ClientRegistration clientRegistration = userRequest.getClientRegistration();
    HttpMethod httpMethod = getHttpMethod(clientRegistration);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
    URI uri = UriComponentsBuilder.fromUriString(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri()).build().toUri();
    RequestEntity<?> request;
    if (HttpMethod.POST.equals(httpMethod)) {
        headers.setContentType(DEFAULT_CONTENT_TYPE);
        MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
        formParameters.add(OAuth2ParameterNames.ACCESS_TOKEN, userRequest.getAccessToken().getTokenValue());
        request = new RequestEntity<>(formParameters, headers, httpMethod, uri);
    } else {
        headers.setBearerAuth(userRequest.getAccessToken().getTokenValue());
        request = new RequestEntity<>(headers, httpMethod, uri);
    }
    return request;
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) URI(java.net.URI) HttpMethod(org.springframework.http.HttpMethod)

Aggregations

Test (org.junit.jupiter.api.Test)28 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)22 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)16 HashMap (java.util.HashMap)6 OAuth2UserRequest (org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest)6 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)6 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)5 MockResponse (okhttp3.mockwebserver.MockResponse)4 HttpHeaders (org.springframework.http.HttpHeaders)4 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)4 OAuth2UserAuthority (org.springframework.security.oauth2.core.user.OAuth2UserAuthority)4 Map (java.util.Map)3 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)3 DefaultOAuth2User (org.springframework.security.oauth2.core.user.DefaultOAuth2User)3 LinkedHashSet (java.util.LinkedHashSet)2 Set (java.util.Set)2 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)2 GrantedAuthoritiesMapper (org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper)2 OAuth2AuthorizationCodeGrantRequest (org.springframework.security.oauth2.client.endpoint.OAuth2AuthorizationCodeGrantRequest)2