List of usage examples for org.springframework.security.oauth2.common.exceptions InvalidRequestException InvalidRequestException
public InvalidRequestException(String msg)
From source file:org.mitre.oauth2.service.impl.BlacklistAwareRedirectResolver.java
@Override public String resolveRedirect(String requestedRedirect, ClientDetails client) throws OAuth2Exception { String redirect = super.resolveRedirect(requestedRedirect, client); if (blacklistService.isBlacklisted(redirect)) { // don't let it go through throw new InvalidRequestException("The supplied redirect_uri is not allowed on this server."); } else {/*from ww w .java 2 s . c o m*/ // not blacklisted, passed the parent test, we're fine return redirect; } }
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 . j a va2 s. co m*/ 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/* ww w . j a v a 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:com.hundsun.sso.controller.OAuthRestController.java
@RequestMapping(value = "/oauth/rest_token", method = RequestMethod.POST) @ResponseBody//from w ww .j a v a 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 www. j a v a 2s . 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:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java
private String appendAccessToken(AuthorizationRequest authorizationRequest, OAuth2AccessToken accessToken) { Map<String, Object> vars = new LinkedHashMap<>(); Map<String, String> keys = new HashMap<>(); if (isNull(accessToken)) { throw new InvalidRequestException("An implicit grant could not be made"); }//from w ww . j a va 2 s.c o m vars.put("access_token", accessToken.getValue()); vars.put("token_type", accessToken.getTokenType()); String state = authorizationRequest.getState(); if (nonNull(state)) { vars.put("state", state); } Date expiration = accessToken.getExpiration(); if (nonNull(expiration)) { long expires_in = (expiration.getTime() - System.currentTimeMillis()) / 1000; vars.put("expires_in", expires_in); } String originalScope = authorizationRequest.getRequestParameters().get(OAuth2Utils.SCOPE); if (isNull(originalScope) || !OAuth2Utils.parseParameterList(originalScope).equals(accessToken.getScope())) { vars.put("scope", OAuth2Utils.formatParameterList(accessToken.getScope())); } Map<String, Object> additionalInformation = accessToken.getAdditionalInformation(); for (String key : additionalInformation.keySet()) { Object value = additionalInformation.get(key); if (nonNull(value)) { keys.put("extra_" + key, key); vars.put("extra_" + key, value); } } // Do not include the refresh token (even if there is one) return append(authorizationRequest.getRedirectUri(), vars, keys, true); }
From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java
private MultiValueMap<String, String> getParametersForTokenRequest(AuthorizationCodeResourceDetails resource, AccessTokenRequest request) {/*ww w . j a v a 2 s. com*/ MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("grant_type", "authorization_code"); form.set("code", request.getAuthorizationCode()); Object preservedState = request.getPreservedState(); if (request.getStateKey() != null || stateMandatory) { // The token endpoint has no use for the state so we don't send it back, but we are using it // for CSRF detection client side... if (preservedState == null) { throw new InvalidRequestException( "Possible CSRF detected - state parameter was required but no state could be found"); } } // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to // resource.getRedirectUri() String redirectUri = null; // Get the redirect uri from the stored state if (preservedState instanceof String) { // Use the preserved state in preference if it is there // TODO: treat redirect URI as a special kind of state (this is a historical mini hack) redirectUri = String.valueOf(preservedState); } else { redirectUri = resource.getRedirectUri(request); } if (redirectUri != null && !"NONE".equals(redirectUri)) { form.set("redirect_uri", redirectUri); } return form; }
From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java
private MultiValueMap<String, String> getParametersForTokenRequest( final AuthorizationCodeResourceDetails resource, final AccessTokenRequest request) { MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set("grant_type", "authorization_code"); form.set("code", request.getAuthorizationCode()); Object preservedState = request.getPreservedState(); if (request.getStateKey() != null) { // The token endpoint has no use for the state so we don't send it back, but we are using it // for CSRF detection client side... if (preservedState == null) { throw new InvalidRequestException( "Possible CSRF detected - state parameter was present but no state could be found"); }//from w w w . j a v a2 s . c om } // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to // resource.getRedirectUri() String redirectUri; // Get the redirect uri from the stored state if (preservedState instanceof String) { // Use the preserved state in preference if it is there // TODO: treat redirect URI as a special kind of state (this is a historical mini hack) redirectUri = String.valueOf(preservedState); } else { redirectUri = resource.getRedirectUri(request); } if (redirectUri != null && !"NONE".equals(redirectUri)) { form.set("redirect_uri", redirectUri); } return form; }
From source file:com.zhm.config.MyAuthorizationCodeAccessTokenProvider.java
private MultiValueMap<String, String> getParametersForAuthorizeRequest( AuthorizationCodeResourceDetails resource, AccessTokenRequest request) { MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.set("response_type", "code"); form.set("client_id", resource.getClientId()); if (request.get("scope") != null) { form.set("scope", request.getFirst("scope")); } else {/*from w ww . j a v a2 s . c o m*/ form.set("scope", OAuth2Utils.formatParameterList(resource.getScope())); } // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to // resource.getRedirectUri() String redirectUri = resource.getPreEstablishedRedirectUri(); Object preservedState = request.getPreservedState(); if (redirectUri == null && preservedState != null) { // no pre-established redirect uri: use the preserved state // TODO: treat redirect URI as a special kind of state (this is a historical mini hack) redirectUri = String.valueOf(preservedState); } else { redirectUri = request.getCurrentUri(); } String stateKey = request.getStateKey(); if (stateKey != null) { form.set("state", stateKey); if (preservedState == null) { throw new InvalidRequestException( "Possible CSRF detected - state parameter was present but no state could be found"); } } if (redirectUri != null) { form.set("redirect_uri", redirectUri); } return form; }
From source file:com.emergya.spring.security.oauth.google.GoogleAuthorizationCodeAccessTokenProvider.java
private MultiValueMap<String, String> getParametersForAuthorizeRequest(GoogleAuthCodeResourceDetails resource, AccessTokenRequest request) {/*from w w w . j a v a2 s . com*/ MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); form.set("response_type", "code"); form.set("client_id", resource.getClientId()); if (request.get("scope") != null) { form.set("scope", request.getFirst("scope")); } else { form.set("scope", OAuth2Utils.formatParameterList(resource.getScope())); } // Extracting the redirect URI from a saved request should ignore the current URI, so it's not simply a call to // resource.getRedirectUri() String redirectUri = resource.getPreEstablishedRedirectUri(); Object preservedState = request.getPreservedState(); if (redirectUri == null && preservedState != null) { // no pre-established redirect uri: use the preserved state // TODO: treat redirect URI as a special kind of state (this is a historical mini hack) redirectUri = String.valueOf(preservedState); } else { redirectUri = request.getCurrentUri(); } String stateKey = request.getStateKey(); if (stateKey != null) { form.set("state", stateKey); if (preservedState == null) { throw new InvalidRequestException( "Possible CSRF detected - state parameter was present but no state could be found"); } } form.set("approval_prompt", resource.getApprovalPrompt()); if (StringUtils.isEmpty(resource.getLoginHint())) { form.set("login_hint", resource.getLoginHint()); } if (redirectUri != null) { form.set("redirect_uri", redirectUri); } return form; }