Search in sources :

Example 1 with OAuth2Error

use of com.nimbusds.oauth2.sdk.OAuth2Error in project spring-security by spring-projects.

the class NimbusAuthorizationCodeTokenResponseClient method getTokenResponse.

private com.nimbusds.oauth2.sdk.TokenResponse getTokenResponse(AuthorizationGrant authorizationCodeGrant, URI tokenUri, ClientAuthentication clientAuthentication) {
    try {
        // Send the Access Token request
        TokenRequest tokenRequest = new TokenRequest(tokenUri, clientAuthentication, authorizationCodeGrant);
        HTTPRequest httpRequest = tokenRequest.toHTTPRequest();
        httpRequest.setAccept(MediaType.APPLICATION_JSON_VALUE);
        httpRequest.setConnectTimeout(30000);
        httpRequest.setReadTimeout(30000);
        return com.nimbusds.oauth2.sdk.TokenResponse.parse(httpRequest.send());
    } catch (ParseException | IOException ex) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE, "An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response: " + ex.getMessage(), null);
        throw new OAuth2AuthorizationException(oauth2Error, ex);
    }
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) HTTPRequest(com.nimbusds.oauth2.sdk.http.HTTPRequest) TokenRequest(com.nimbusds.oauth2.sdk.TokenRequest) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) ParseException(com.nimbusds.oauth2.sdk.ParseException) IOException(java.io.IOException)

Example 2 with OAuth2Error

use of com.nimbusds.oauth2.sdk.OAuth2Error in project spring-security by spring-projects.

the class OAuth2AccessTokenResponseBodyExtractor method oauth2AccessTokenResponse.

private static Mono<AccessTokenResponse> oauth2AccessTokenResponse(TokenResponse tokenResponse) {
    if (tokenResponse.indicatesSuccess()) {
        return Mono.just(tokenResponse).cast(AccessTokenResponse.class);
    }
    TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
    ErrorObject errorObject = tokenErrorResponse.getErrorObject();
    OAuth2Error oauth2Error = getOAuth2Error(errorObject);
    return Mono.error(new OAuth2AuthorizationException(oauth2Error));
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) TokenErrorResponse(com.nimbusds.oauth2.sdk.TokenErrorResponse) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error)

Example 3 with OAuth2Error

use of com.nimbusds.oauth2.sdk.OAuth2Error 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(HttpStatusCode::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) HttpStatusCode(org.springframework.http.HttpStatusCode) 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) 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 4 with OAuth2Error

use of com.nimbusds.oauth2.sdk.OAuth2Error in project spring-security by spring-projects.

the class OAuth2ErrorResponseErrorHandler method readErrorFromWwwAuthenticate.

private OAuth2Error readErrorFromWwwAuthenticate(HttpHeaders headers) {
    String wwwAuthenticateHeader = headers.getFirst(HttpHeaders.WWW_AUTHENTICATE);
    if (!StringUtils.hasText(wwwAuthenticateHeader)) {
        return null;
    }
    BearerTokenError bearerTokenError = getBearerToken(wwwAuthenticateHeader);
    if (bearerTokenError == null) {
        return new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR, null, null);
    }
    String errorCode = (bearerTokenError.getCode() != null) ? bearerTokenError.getCode() : OAuth2ErrorCodes.SERVER_ERROR;
    String errorDescription = bearerTokenError.getDescription();
    String errorUri = (bearerTokenError.getURI() != null) ? bearerTokenError.getURI().toString() : null;
    return new OAuth2Error(errorCode, errorDescription, errorUri);
}
Also used : OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) BearerTokenError(com.nimbusds.oauth2.sdk.token.BearerTokenError)

Aggregations

OAuth2Error (org.springframework.security.oauth2.core.OAuth2Error)4 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)2 OAuth2AuthorizationException (org.springframework.security.oauth2.core.OAuth2AuthorizationException)2 ParseException (com.nimbusds.oauth2.sdk.ParseException)1 TokenErrorResponse (com.nimbusds.oauth2.sdk.TokenErrorResponse)1 TokenRequest (com.nimbusds.oauth2.sdk.TokenRequest)1 HTTPRequest (com.nimbusds.oauth2.sdk.http.HTTPRequest)1 BearerTokenError (com.nimbusds.oauth2.sdk.token.BearerTokenError)1 UserInfoErrorResponse (com.nimbusds.openid.connect.sdk.UserInfoErrorResponse)1 IOException (java.io.IOException)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 Set (java.util.Set)1 JSONObject (net.minidev.json.JSONObject)1 ParameterizedTypeReference (org.springframework.core.ParameterizedTypeReference)1 HttpHeaders (org.springframework.http.HttpHeaders)1 HttpStatusCode (org.springframework.http.HttpStatusCode)1 MediaType (org.springframework.http.MediaType)1 GrantedAuthority (org.springframework.security.core.GrantedAuthority)1 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)1