List of usage examples for org.springframework.security.oauth2.common.exceptions UnsupportedResponseTypeException UnsupportedResponseTypeException
public UnsupportedResponseTypeException(String msg)
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 2 s. com 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:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java
@Override protected void configure() { setControllerPath("oauth"); get("authorize", (req, resp) -> { Map<String, String> parameters = MapUtils.createOneDimMap(req.getQueryParams()); AuthorizationRequest authorizationRequest = requestFactory.createAuthorizationRequest(parameters); Set<String> responseTypes = authorizationRequest.getResponseTypes(); if (!responseTypes.contains("token") && !responseTypes.contains("code")) { throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes); }//from www . j av a 2 s .c om if (isNull(authorizationRequest.getClientId())) { throw new InvalidClientException("A client id must be provided"); } ClientDetails client = clientDetailsService.loadClientByClientId(authorizationRequest.getClientId()); String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); if (isEmpty(resolvedRedirect)) { throw new RedirectMismatchException( "A redirectUri must be either supplied or preconfigured in the ClientDetails"); } authorizationRequest.setRedirectUri(resolvedRedirect); requestValidator.validateScope(authorizationRequest, client); authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, null); boolean approved = userApprovalHandler.isApproved(authorizationRequest, null); authorizationRequest.setApproved(approved); if (authorizationRequest.isApproved()) { if (responseTypes.contains("token")) { resp.status(HttpStatus.FOUND); resp.header(HeaderName.LOCATION, getImplicitGrantResponse(authorizationRequest)); } if (responseTypes.contains("code")) { resp.status(HttpStatus.FOUND); resp.header(HeaderName.LOCATION, getAuthorizationCodeResponse(authorizationRequest)); } } }); }
From source file:org.joyrest.oauth2.endpoint.AuthorizationEndpoint.java
private String getImplicitGrantResponse(AuthorizationRequest authorizationRequest) { try {// w w w. j a v a2 s . c om TokenRequest tokenRequest = requestFactory.createTokenRequest(authorizationRequest, "implicit"); OAuth2Request storedOAuth2Request = requestFactory.createOAuth2Request(authorizationRequest); OAuth2AccessToken accessToken = getAccessTokenForImplicitGrant(tokenRequest, storedOAuth2Request); if (isNull(accessToken)) { throw new UnsupportedResponseTypeException("Unsupported response type: token"); } return appendAccessToken(authorizationRequest, accessToken); } catch (OAuth2Exception e) { return getUnsuccessfulRedirect(authorizationRequest, e, true); } }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
@RequestMapping(value = "/oauth/authorize") public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal, HttpServletRequest request) { ClientDetails client;//from w w w . j a v a 2 s . com String clientId; try { clientId = parameters.get("client_id"); client = getClientServiceExtention().loadClientByClientId(clientId, IdentityZoneHolder.get().getId()); } catch (NoSuchClientException x) { throw new InvalidClientException(x.getMessage()); } // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should // query off of the authorization request instead of referring back to the parameters map. The contents of the // parameters map will be stored without change in the AuthorizationRequest object once it is created. AuthorizationRequest authorizationRequest; try { authorizationRequest = getOAuth2RequestFactory().createAuthorizationRequest(parameters); } catch (DisallowedIdpException x) { return switchIdp(model, client, clientId, request); } Set<String> responseTypes = authorizationRequest.getResponseTypes(); String grantType = deriveGrantTypeFromResponseType(responseTypes); if (!supported_response_types.containsAll(responseTypes)) { throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes); } if (authorizationRequest.getClientId() == null) { throw new InvalidClientException("A client id must be provided"); } String resolvedRedirect = ""; try { String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); try { resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); } catch (RedirectMismatchException rme) { throw new RedirectMismatchException( "Invalid redirect " + redirectUriParameter + " did not match one of the registered values"); } if (!StringUtils.hasText(resolvedRedirect)) { throw new RedirectMismatchException( "A redirectUri must be either supplied or preconfigured in the ClientDetails"); } boolean isAuthenticated = (principal instanceof Authentication) && ((Authentication) principal).isAuthenticated(); if (!isAuthenticated) { throw new InsufficientAuthenticationException( "User must be authenticated with Spring Security before authorization can be completed."); } if (!(responseTypes.size() > 0)) { return new ModelAndView(new RedirectView( addQueryParameter(addQueryParameter(resolvedRedirect, "error", "invalid_request"), "error_description", "Missing response_type in authorization request"))); } authorizationRequest.setRedirectUri(resolvedRedirect); // We intentionally only validate the parameters requested by the client (ignoring any data that may have // been added to the request by the manager). oauth2RequestValidator.validateScope(authorizationRequest, client); // Some systems may allow for approval decisions to be remembered or approved by default. Check for // such logic here, and set the approved flag on the authorization request accordingly. authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, (Authentication) principal); boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal); authorizationRequest.setApproved(approved); // Validation is all done, so we can check for auto approval... if (authorizationRequest.isApproved()) { if (responseTypes.contains("token") || responseTypes.contains("id_token")) { return getImplicitGrantOrHybridResponse(authorizationRequest, (Authentication) principal, grantType); } if (responseTypes.contains("code")) { return new ModelAndView( getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal)); } } if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) { return new ModelAndView( new RedirectView(addFragmentComponent(resolvedRedirect, "error=interaction_required"))); } else { // Place auth request into the model so that it is stored in the session // for approveOrDeny to use. That way we make sure that auth request comes from the session, // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session. model.put(AUTHORIZATION_REQUEST, authorizationRequest); model.put("original_uri", UrlUtils.buildFullRequestUrl(request)); model.put(ORIGINAL_AUTHORIZATION_REQUEST, unmodifiableMap(authorizationRequest)); return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal); } } catch (RedirectMismatchException e) { sessionStatus.setComplete(); throw e; } catch (Exception e) { sessionStatus.setComplete(); logger.debug("Unable to handle /oauth/authorize, internal error", e); if ("none".equals(authorizationRequest.getRequestParameters().get("prompt"))) { return new ModelAndView( new RedirectView(addFragmentComponent(resolvedRedirect, "error=internal_server_error"))); } throw e; } }
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
private ModelAndView getImplicitGrantOrHybridResponse(AuthorizationRequest authorizationRequest, Authentication authentication, String grantType) { OAuth2AccessToken accessToken;/* www . j a v a 2 s . c o m*/ try { TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, GRANT_TYPE_IMPLICIT); Map<String, String> requestParameters = new HashMap<>(authorizationRequest.getRequestParameters()); requestParameters.put(GRANT_TYPE, grantType); authorizationRequest.setRequestParameters(requestParameters); OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest); accessToken = getAccessTokenForImplicitGrantOrHybrid(tokenRequest, storedOAuth2Request, grantType); if (accessToken == null) { throw new UnsupportedResponseTypeException("Unsupported response type: token or id_token"); } return new ModelAndView(new RedirectView( buildRedirectURI(authorizationRequest, accessToken, authentication), false, true, false)); } catch (OAuth2Exception e) { return new ModelAndView( new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, true), false, true, false)); } }
From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java
@RequestMapping(value = "/oauth/authorize") public ModelAndView authorize(Map<String, Object> model, @RequestParam Map<String, String> parameters, SessionStatus sessionStatus, Principal principal) { logger.info("paramters:" + parameters.toString()); logger.info("model:" + model.toString()); // Pull out the authorization request first, using the OAuth2RequestFactory. All further logic should // query off of the authorization request instead of referring back to the parameters map. The contents of the // parameters map will be stored without change in the AuthorizationRequest object once it is created. AuthorizationRequest authorizationRequest = getOAuth2RequestFactory() .createAuthorizationRequest(parameters); Set<String> responseTypes = authorizationRequest.getResponseTypes(); if (!responseTypes.contains("token") && !responseTypes.contains("code")) { throw new UnsupportedResponseTypeException("Unsupported response types: " + responseTypes); }/* w w w . ja va 2 s . c o m*/ if (authorizationRequest.getClientId() == null) { throw new InvalidClientException("A client id must be provided"); } try { if (!(principal instanceof Authentication) || !((Authentication) principal).isAuthenticated()) { throw new InsufficientAuthenticationException( "User must be authenticated with Spring Security before authorization can be completed."); } ClientDetails client = getClientDetailsService() .loadClientByClientId(authorizationRequest.getClientId()); // The resolved redirect URI is either the redirect_uri from the parameters or the one from // clientDetails. Either way we need to store it on the AuthorizationRequest. String redirectUriParameter = authorizationRequest.getRequestParameters().get(OAuth2Utils.REDIRECT_URI); String resolvedRedirect = redirectResolver.resolveRedirect(redirectUriParameter, client); if (!StringUtils.hasText(resolvedRedirect)) { throw new RedirectMismatchException( "A redirectUri must be either supplied or preconfigured in the ClientDetails"); } authorizationRequest.setRedirectUri(resolvedRedirect); // We intentionally only validate the parameters requested by the client (ignoring any data that may have // been added to the request by the manager). oauth2RequestValidator.validateScope(authorizationRequest, client); // Some systems may allow for approval decisions to be remembered or approved by default. Check for // such logic here, and set the approved flag on the authorization request accordingly. authorizationRequest = userApprovalHandler.checkForPreApproval(authorizationRequest, (Authentication) principal); // TODO: is this call necessary? boolean approved = userApprovalHandler.isApproved(authorizationRequest, (Authentication) principal); authorizationRequest.setApproved(approved); // Validation is all done, so we can check for auto approval... if (authorizationRequest.isApproved()) { if (responseTypes.contains("token")) { return getImplicitGrantResponse(authorizationRequest); } if (responseTypes.contains("code")) { return new ModelAndView( getAuthorizationCodeResponse(authorizationRequest, (Authentication) principal)); } } // Place auth request into the model so that it is stored in the session // for approveOrDeny to use. That way we make sure that auth request comes from the session, // so any auth request parameters passed to approveOrDeny will be ignored and retrieved from the session. model.put("authorizationRequest", authorizationRequest); return getUserApprovalPageResponse(model, authorizationRequest, (Authentication) principal); } catch (RuntimeException e) { sessionStatus.setComplete(); throw e; } }
From source file:org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.java
private ModelAndView getImplicitGrantResponse(AuthorizationRequest authorizationRequest) { try {/* ww w . j a va2 s . c o m*/ TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(authorizationRequest, "implicit"); OAuth2Request storedOAuth2Request = getOAuth2RequestFactory().createOAuth2Request(authorizationRequest); OAuth2AccessToken accessToken = getAccessTokenForImplicitGrant(tokenRequest, storedOAuth2Request); if (accessToken == null) { throw new UnsupportedResponseTypeException("Unsupported response type: token"); } return new ModelAndView( new RedirectView(appendAccessToken(authorizationRequest, accessToken), false, true, false)); } catch (OAuth2Exception e) { return new ModelAndView( new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, true), false, true, false)); } }