Search in sources :

Example 6 with UserInfoEndpoint

use of org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails.UserInfoEndpoint in project spring-boot by spring-projects.

the class OAuth2ClientPropertiesRegistrationAdapterTests method testIssuerConfiguration.

private void testIssuerConfiguration(OAuth2ClientProperties.Registration registration, String providerId, int errorResponseCount, int numberOfRequests) throws Exception {
    this.server = new MockWebServer();
    this.server.start();
    String issuer = this.server.url("").toString();
    setupMockResponsesWithErrors(issuer, errorResponseCount);
    OAuth2ClientProperties properties = new OAuth2ClientProperties();
    Provider provider = new Provider();
    provider.setIssuerUri(issuer);
    properties.getProvider().put(providerId, provider);
    properties.getRegistration().put("okta", registration);
    Map<String, ClientRegistration> registrations = OAuth2ClientPropertiesRegistrationAdapter.getClientRegistrations(properties);
    ClientRegistration adapted = registrations.get("okta");
    ProviderDetails providerDetails = adapted.getProviderDetails();
    assertThat(adapted.getClientAuthenticationMethod()).isEqualTo(ClientAuthenticationMethod.CLIENT_SECRET_BASIC);
    assertThat(adapted.getAuthorizationGrantType()).isEqualTo(AuthorizationGrantType.AUTHORIZATION_CODE);
    assertThat(adapted.getRegistrationId()).isEqualTo("okta");
    assertThat(adapted.getClientName()).isEqualTo(issuer);
    assertThat(adapted.getScopes()).isNull();
    assertThat(providerDetails.getAuthorizationUri()).isEqualTo("https://example.com/o/oauth2/v2/auth");
    assertThat(providerDetails.getTokenUri()).isEqualTo("https://example.com/oauth2/v4/token");
    assertThat(providerDetails.getJwkSetUri()).isEqualTo("https://example.com/oauth2/v3/certs");
    UserInfoEndpoint userInfoEndpoint = providerDetails.getUserInfoEndpoint();
    assertThat(userInfoEndpoint.getUri()).isEqualTo("https://example.com/oauth2/v3/userinfo");
    assertThat(userInfoEndpoint.getAuthenticationMethod()).isEqualTo(org.springframework.security.oauth2.core.AuthenticationMethod.HEADER);
    assertThat(this.server.getRequestCount()).isEqualTo(numberOfRequests);
}
Also used : ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) MockWebServer(okhttp3.mockwebserver.MockWebServer) UserInfoEndpoint(org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails.UserInfoEndpoint) ProviderDetails(org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails) Provider(org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.Provider)

Example 7 with UserInfoEndpoint

use of org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails.UserInfoEndpoint 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 8 with UserInfoEndpoint

use of org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails.UserInfoEndpoint 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)

Aggregations

ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)6 ProviderDetails (org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails)6 UserInfoEndpoint (org.springframework.security.oauth2.client.registration.ClientRegistration.ProviderDetails.UserInfoEndpoint)6 Test (org.junit.jupiter.api.Test)5 Registration (org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.Registration)5 Provider (org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties.Provider)3 Map (java.util.Map)2 MockWebServer (okhttp3.mockwebserver.MockWebServer)2 GrantedAuthority (org.springframework.security.core.GrantedAuthority)2 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)2 OAuth2AccessToken (org.springframework.security.oauth2.core.OAuth2AccessToken)2 OAuth2AuthenticationException (org.springframework.security.oauth2.core.OAuth2AuthenticationException)2 OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)2 DefaultOAuth2User (org.springframework.security.oauth2.core.user.DefaultOAuth2User)2 OAuth2UserAuthority (org.springframework.security.oauth2.core.user.OAuth2UserAuthority)2 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)1 UserInfoErrorResponse (com.nimbusds.openid.connect.sdk.UserInfoErrorResponse)1 HashSet (java.util.HashSet)1 LinkedHashSet (java.util.LinkedHashSet)1 Set (java.util.Set)1