Example usage for org.springframework.security.oauth2.common.exceptions UnsupportedGrantTypeException UnsupportedGrantTypeException

List of usage examples for org.springframework.security.oauth2.common.exceptions UnsupportedGrantTypeException UnsupportedGrantTypeException

Introduction

In this page you can find the example usage for org.springframework.security.oauth2.common.exceptions UnsupportedGrantTypeException UnsupportedGrantTypeException.

Prototype

public UnsupportedGrantTypeException(String msg) 

Source Link

Usage

From source file:org.springframework.security.oauth2.common.exceptions.OAuth2ExceptionJackson2Deserializer.java

@Override
public OAuth2Exception deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {

    JsonToken t = jp.getCurrentToken();//from w  w w  .  ja v a  2s.c om
    if (t == JsonToken.START_OBJECT) {
        t = jp.nextToken();
    }
    Map<String, Object> errorParams = new HashMap<String, Object>();
    for (; t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        // Must point to field name
        String fieldName = jp.getCurrentName();
        // And then the value...
        t = jp.nextToken();
        // Note: must handle null explicitly here; value deserializers won't
        Object value;
        if (t == JsonToken.VALUE_NULL) {
            value = null;
        }
        // Some servers might send back complex content
        else if (t == JsonToken.START_ARRAY) {
            value = jp.readValueAs(List.class);
        } else if (t == JsonToken.START_OBJECT) {
            value = jp.readValueAs(Map.class);
        } else {
            value = jp.getText();
        }
        errorParams.put(fieldName, value);
    }

    Object errorCode = errorParams.get("error");
    String errorMessage = errorParams.containsKey("error_description")
            ? errorParams.get("error_description").toString()
            : null;
    if (errorMessage == null) {
        errorMessage = errorCode == null ? "OAuth Error" : errorCode.toString();
    }

    OAuth2Exception ex;
    if ("invalid_client".equals(errorCode)) {
        ex = new InvalidClientException(errorMessage);
    } else if ("unauthorized_client".equals(errorCode)) {
        ex = new UnauthorizedUserException(errorMessage);
    } else if ("invalid_grant".equals(errorCode)) {
        if (errorMessage.toLowerCase().contains("redirect") && errorMessage.toLowerCase().contains("match")) {
            ex = new RedirectMismatchException(errorMessage);
        } else {
            ex = new InvalidGrantException(errorMessage);
        }
    } else if ("invalid_scope".equals(errorCode)) {
        ex = new InvalidScopeException(errorMessage);
    } else if ("invalid_token".equals(errorCode)) {
        ex = new InvalidTokenException(errorMessage);
    } else if ("invalid_request".equals(errorCode)) {
        ex = new InvalidRequestException(errorMessage);
    } else if ("redirect_uri_mismatch".equals(errorCode)) {
        ex = new RedirectMismatchException(errorMessage);
    } else if ("unsupported_grant_type".equals(errorCode)) {
        ex = new UnsupportedGrantTypeException(errorMessage);
    } else if ("unsupported_response_type".equals(errorCode)) {
        ex = new UnsupportedResponseTypeException(errorMessage);
    } else if ("insufficient_scope".equals(errorCode)) {
        ex = new InsufficientScopeException(errorMessage,
                OAuth2Utils.parseParameterList((String) errorParams.get("scope")));
    } else if ("access_denied".equals(errorCode)) {
        ex = new UserDeniedAuthorizationException(errorMessage);
    } else {
        ex = new OAuth2Exception(errorMessage);
    }

    Set<Map.Entry<String, Object>> entries = errorParams.entrySet();
    for (Map.Entry<String, Object> entry : entries) {
        String key = entry.getKey();
        if (!"error".equals(key) && !"error_description".equals(key)) {
            Object value = entry.getValue();
            ex.addAdditionalInformation(key, value == null ? null : value.toString());
        }
    }

    return ex;

}

From source file:com.monkeyk.sos.web.controller.OAuthRestController.java

@RequestMapping(value = "/oauth2/rest_token", method = RequestMethod.POST)
@ResponseBody/* w w w .  j ava 2  s.co m*/
public OAuth2AccessToken postAccessToken(@RequestBody Map<String, String> parameters) {

    String clientId = getClientId(parameters);
    ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);

    TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);

    if (clientId != null && !"".equals(clientId)) {
        // Only validate the client details if a client authenticated during this
        // request.
        if (!clientId.equals(tokenRequest.getClientId())) {
            // double check to make sure that the client ID in the token request is the same as that in the
            // authenticated client
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }
    }

    if (authenticatedClient != null) {
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
    }

    final String grantType = tokenRequest.getGrantType();
    if (!StringUtils.hasText(grantType)) {
        throw new InvalidRequestException("Missing grant type");
    }
    if ("implicit".equals(grantType)) {
        throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
    }

    if (isAuthCodeRequest(parameters)) {
        // The scope was requested or determined during the authorization step
        if (!tokenRequest.getScope().isEmpty()) {
            LOG.debug("Clearing scope of incoming token request");
            tokenRequest.setScope(Collections.<String>emptySet());
        }
    }

    if (isRefreshTokenRequest(parameters)) {
        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
    }

    OAuth2AccessToken token = getTokenGranter(grantType).grant(grantType, tokenRequest);
    if (token == null) {
        throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType);
    }

    return token;

}

From source file:com.hundsun.sso.controller.OAuthRestController.java

@RequestMapping(value = "/oauth/rest_token", method = RequestMethod.POST)
@ResponseBody/*from   w w w .  j  ava 2 s. c om*/
public OAuth2AccessToken postAccessToken(@RequestBody Map<String, String> parameters) {

    String clientId = getClientId(parameters);
    ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);

    TokenRequest tokenRequest = oAuth2RequestFactory.createTokenRequest(parameters, authenticatedClient);

    if (clientId != null && !"".equals(clientId)) {
        // Only validate the client details if a client authenticated during this
        // request.
        if (!clientId.equals(tokenRequest.getClientId())) {
            // double check to make sure that the client ID in the token request is the same as that in the
            // authenticated client
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }
    }

    if (authenticatedClient != null) {
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
    }

    final String grantType = tokenRequest.getGrantType();
    if (!StringUtils.hasText(grantType)) {
        throw new InvalidRequestException("Missing grant type");
    }
    if ("implicit".equals(grantType)) {
        throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
    }

    if (isAuthCodeRequest(parameters)) {
        // The scope was requested or determined during the authorization step
        if (!tokenRequest.getScope().isEmpty()) {
            LOG.debug("Clearing scope of incoming token request");
            tokenRequest.setScope(Collections.<String>emptySet());
        }
    }

    if (isRefreshTokenRequest(parameters)) {
        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
    }

    OAuth2AccessToken token = getTokenGranter(grantType).grant(grantType, tokenRequest);
    if (token == null) {
        throw new UnsupportedGrantTypeException("Unsupported grant type: " + grantType);
    }

    return token;

}

From source file:org.joyrest.oauth2.endpoint.TokenEndpoint.java

@Override
protected void configure() {
    setControllerPath("oauth");

    post("token", (req, resp) -> {
        Authentication principal = basicAuthenticator.authenticate(req);

        String clientId = getClientId(principal);
        ClientDetails authenticatedClient = clientDetailsService.loadClientByClientId(clientId);

        Map<String, String> parameters = MapUtils.createOneDimMap(req.getQueryParams());
        TokenRequest tokenRequest = requestFactory.createTokenRequest(parameters, authenticatedClient);

        // Only validate the client details if a client authenticated during this request.
        if (!isEmpty(clientId) && !clientId.equals(tokenRequest.getClientId())) {
            throw new InvalidClientException("Given client ID does not match authenticated client");
        }//from   ww w.j av a  2 s.  c  o m

        if (nonNull(authenticatedClient)) {
            requestValidator.validateScope(tokenRequest, authenticatedClient);
        }

        if (!isEmpty(tokenRequest.getGrantType())) {
            throw new InvalidRequestException("Missing grant type");
        }

        if (tokenRequest.getGrantType().equals("implicit")) {
            throw new InvalidGrantException("Implicit grant type not supported from token endpoint");
        }

        // The scope was requested or determined during the authorization step
        if (isAuthCodeRequest(parameters) && nonEmpty(tokenRequest.getScope())) {
            tokenRequest.setScope(emptySet());
        }

        // A refresh token has its own default scopes, so we should ignore any added by the factory here.
        if (isRefreshTokenRequest(parameters)) {
            tokenRequest.setScope(OAuth2Utils.parseParameterList(parameters.get(OAuth2Utils.SCOPE)));
        }

        OAuth2AccessToken token = tokenGranter.grant(tokenRequest.getGrantType(), tokenRequest);
        if (isNull(token)) {
            throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType());
        }

        createResponse(resp, token);

    }, Resp(OAuth2AccessToken.class)).produces(JSON);
}

From source file:com.hundsun.sso.controller.OAuthRestController.java

protected TokenGranter getTokenGranter(String grantType) {

    if ("authorization_code".equals(grantType)) {
        return new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsService,
                this.oAuth2RequestFactory);
    } else if ("password".equals(grantType)) {
        return new ResourceOwnerPasswordTokenGranter(getAuthenticationManager(), tokenServices,
                clientDetailsService, this.oAuth2RequestFactory);
    } else if ("refresh_token".equals(grantType)) {
        return new RefreshTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory);
    } else if ("client_credentials".equals(grantType)) {
        return new ClientCredentialsTokenGranter(tokenServices, clientDetailsService,
                this.oAuth2RequestFactory);
    } else if ("implicit".equals(grantType)) {
        return new ImplicitTokenGranter(tokenServices, clientDetailsService, this.oAuth2RequestFactory);
    } else {//from  ww w .ja v a 2 s  . c  om
        throw new UnsupportedGrantTypeException("Unsupport grant_type: " + grantType);
    }
}

From source file:com.orcid.api.common.server.delegator.impl.OrcidClientCredentialEndPointDelegatorImpl.java

protected OAuth2AccessToken generateToken(Authentication client, Set<String> scopes, String code,
        String redirectUri, String grantType, String refreshToken, String state) {
    String clientId = client.getName();
    Map<String, String> authorizationParameters = new HashMap<String, String>();

    if (scopes != null) {
        String scopesString = StringUtils.join(scopes, ' ');
        authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
    }/*from   w  w  w  .  j  a  v a  2 s  . c o m*/

    authorizationParameters.put(OAuth2Utils.CLIENT_ID, clientId);
    if (code != null) {
        authorizationParameters.put("code", code);
        OrcidOauth2AuthoriziationCodeDetail authorizationCodeEntity = orcidOauth2AuthoriziationCodeDetailDao
                .find(code);

        if (authorizationCodeEntity != null) {
            if (orcidOauth2AuthoriziationCodeDetailDao.isPersistentToken(code)) {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "true");
            } else {
                authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
            }

            if (!authorizationParameters.containsKey(OAuth2Utils.SCOPE)
                    || PojoUtil.isEmpty(authorizationParameters.get(OAuth2Utils.SCOPE))) {
                String scopesString = StringUtils.join(authorizationCodeEntity.getScopes(), ' ');
                authorizationParameters.put(OAuth2Utils.SCOPE, scopesString);
            }
        } else {
            authorizationParameters.put(OrcidOauth2Constants.IS_PERSISTENT, "false");
        }
    }
    if (redirectUri != null) {
        authorizationParameters.put(OAuth2Utils.REDIRECT_URI, redirectUri);
    }
    AuthorizationRequest authorizationRequest = getOAuth2RequestFactory()
            .createAuthorizationRequest(authorizationParameters);

    TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, grantType);

    OAuth2AccessToken token = getTokenGranter().grant(grantType, tokenRequest);
    Object params[] = { grantType };
    if (token == null) {
        LOGGER.info(
                "Unsupported grant type for OAuth2: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}",
                new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri });
        throw new UnsupportedGrantTypeException(
                localeManager.resolveMessage("apiError.unsupported_client_type.exception", params));
    }
    LOGGER.info(
            "OAuth2 access token granted: clientId={}, grantType={}, refreshToken={}, code={}, scopes={}, state={}, redirectUri={}, token={}",
            new Object[] { clientId, grantType, refreshToken, code, scopes, state, redirectUri, token });

    return token;
}

From source file:org.cloudfoundry.identity.client.UaaContextFactory.java

/**
 * Authenticates the client and optionally the user and retrieves an access token
 * Token request must be valid, see {@link TokenRequest#isValid()}
 * @param request - a fully configured token request
 * @return an authenticated UAA context with
 * @throws NullPointerException if the request object is null
 * @throws IllegalArgumentException if the token request is invalid
 *//* ww  w .j a  v a2 s . c  om*/
public UaaContext authenticate(TokenRequest request) {
    if (request == null) {
        throw new NullPointerException(TokenRequest.class.getName() + " cannot be null.");
    }
    if (!request.isValid()) {
        throw new IllegalArgumentException("Invalid token request.");
    }
    switch (request.getGrantType()) {
    case CLIENT_CREDENTIALS:
        return authenticateClientCredentials(request);
    case PASSWORD:
    case PASSWORD_WITH_PASSCODE:
        return authenticatePassword(request);
    case AUTHORIZATION_CODE:
        return authenticateAuthCode(request);
    case AUTHORIZATION_CODE_WITH_TOKEN:
        return authenticateAuthCodeWithToken(request);
    case FETCH_TOKEN_FROM_CODE:
        return fetchTokenFromCode(request);
    case SAML2_BEARER:
        return authenticateSaml2BearerAssertion(request);
    default:
        throw new UnsupportedGrantTypeException("Not implemented:" + request.getGrantType());
    }
}