Search in sources :

Example 1 with OAuth2UserAuthority

use of org.springframework.security.oauth2.core.user.OAuth2UserAuthority in project spring-security by spring-projects.

the class DefaultOAuth2UserServiceTests method loadUserWhenUserInfoSuccessResponseThenReturnUser.

@Test
public void loadUserWhenUserInfoSuccessResponseThenReturnUser() {
    // @formatter:off
    String userInfoResponse = "{\n" + "   \"user-name\": \"user1\",\n" + "   \"first-name\": \"first\",\n" + "   \"last-name\": \"last\",\n" + "   \"middle-name\": \"middle\",\n" + "   \"address\": \"address\",\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).userInfoAuthenticationMethod(AuthenticationMethod.HEADER).userNameAttributeName("user-name").build();
    OAuth2User user = this.userService.loadUser(new OAuth2UserRequest(clientRegistration, this.accessToken));
    assertThat(user.getName()).isEqualTo("user1");
    assertThat(user.getAttributes().size()).isEqualTo(6);
    assertThat((String) user.getAttribute("user-name")).isEqualTo("user1");
    assertThat((String) user.getAttribute("first-name")).isEqualTo("first");
    assertThat((String) user.getAttribute("last-name")).isEqualTo("last");
    assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle");
    assertThat((String) user.getAttribute("address")).isEqualTo("address");
    assertThat((String) user.getAttribute("email")).isEqualTo("user1@example.com");
    assertThat(user.getAuthorities().size()).isEqualTo(1);
    assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class);
    OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next();
    assertThat(userAuthority.getAuthority()).isEqualTo("ROLE_USER");
    assertThat(userAuthority.getAttributes()).isEqualTo(user.getAttributes());
}
Also used : OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) Test(org.junit.jupiter.api.Test)

Example 2 with OAuth2UserAuthority

use of org.springframework.security.oauth2.core.user.OAuth2UserAuthority in project spring-security by spring-projects.

the class DefaultReactiveOAuth2UserServiceTests method loadUserWhenUserInfoSuccessResponseThenReturnUser.

@Test
public void loadUserWhenUserInfoSuccessResponseThenReturnUser() {
    // @formatter:off
    String userInfoResponse = "{\n" + "   \"id\": \"user1\",\n" + "   \"first-name\": \"first\",\n" + "   \"last-name\": \"last\",\n" + "   \"middle-name\": \"middle\",\n" + "   \"address\": \"address\",\n" + "   \"email\": \"user1@example.com\"\n" + "}\n";
    // @formatter:on
    enqueueApplicationJsonBody(userInfoResponse);
    OAuth2User user = this.userService.loadUser(oauth2UserRequest()).block();
    assertThat(user.getName()).isEqualTo("user1");
    assertThat(user.getAttributes().size()).isEqualTo(6);
    assertThat((String) user.getAttribute("id")).isEqualTo("user1");
    assertThat((String) user.getAttribute("first-name")).isEqualTo("first");
    assertThat((String) user.getAttribute("last-name")).isEqualTo("last");
    assertThat((String) user.getAttribute("middle-name")).isEqualTo("middle");
    assertThat((String) user.getAttribute("address")).isEqualTo("address");
    assertThat((String) user.getAttribute("email")).isEqualTo("user1@example.com");
    assertThat(user.getAuthorities().size()).isEqualTo(1);
    assertThat(user.getAuthorities().iterator().next()).isInstanceOf(OAuth2UserAuthority.class);
    OAuth2UserAuthority userAuthority = (OAuth2UserAuthority) user.getAuthorities().iterator().next();
    assertThat(userAuthority.getAuthority()).isEqualTo("ROLE_USER");
    assertThat(userAuthority.getAttributes()).isEqualTo(user.getAttributes());
}
Also used : OAuth2User(org.springframework.security.oauth2.core.user.OAuth2User) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority) Test(org.junit.jupiter.api.Test)

Example 3 with OAuth2UserAuthority

use of org.springframework.security.oauth2.core.user.OAuth2UserAuthority in project spring-security by spring-projects.

the class OAuth2AuthenticationTokenMixinTests method asJson.

private static String asJson(Collection<? extends GrantedAuthority> authorities, String classTypeInfo) {
    OAuth2UserAuthority oauth2UserAuthority = null;
    OidcUserAuthority oidcUserAuthority = null;
    List<SimpleGrantedAuthority> simpleAuthorities = new ArrayList<>();
    for (GrantedAuthority authority : authorities) {
        if (authority instanceof OidcUserAuthority) {
            oidcUserAuthority = (OidcUserAuthority) authority;
        } else if (authority instanceof OAuth2UserAuthority) {
            oauth2UserAuthority = (OAuth2UserAuthority) authority;
        } else if (authority instanceof SimpleGrantedAuthority) {
            simpleAuthorities.add((SimpleGrantedAuthority) authority);
        }
    }
    String authoritiesJson = (oidcUserAuthority != null) ? asJson(oidcUserAuthority) : (oauth2UserAuthority != null) ? asJson(oauth2UserAuthority) : "";
    if (!simpleAuthorities.isEmpty()) {
        if (!StringUtils.isEmpty(authoritiesJson)) {
            authoritiesJson += ",";
        }
        authoritiesJson += asJson(simpleAuthorities);
    }
    // @formatter:off
    return "[\n" + "      \"" + classTypeInfo + "\",\n" + "      [" + authoritiesJson + "]\n" + "    ]";
// @formatter:on
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) OidcUserAuthority(org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) ArrayList(java.util.ArrayList) OAuth2UserAuthority(org.springframework.security.oauth2.core.user.OAuth2UserAuthority)

Example 4 with OAuth2UserAuthority

use of org.springframework.security.oauth2.core.user.OAuth2UserAuthority 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 5 with OAuth2UserAuthority

use of org.springframework.security.oauth2.core.user.OAuth2UserAuthority 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

OAuth2UserAuthority (org.springframework.security.oauth2.core.user.OAuth2UserAuthority)5 GrantedAuthority (org.springframework.security.core.GrantedAuthority)3 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)3 OAuth2User (org.springframework.security.oauth2.core.user.OAuth2User)3 Map (java.util.Map)2 Test (org.junit.jupiter.api.Test)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 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)1 UserInfoErrorResponse (com.nimbusds.openid.connect.sdk.UserInfoErrorResponse)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 LinkedHashSet (java.util.LinkedHashSet)1 Set (java.util.Set)1 JSONObject (net.minidev.json.JSONObject)1 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)1 HttpHeaders (org.springframework.http.HttpHeaders)1 HttpStatus (org.springframework.http.HttpStatus)1