List of usage examples for org.springframework.security.oauth2.provider AuthorizationRequest setRedirectUri
public void setRedirectUri(String redirectUri)
From source file:org.cloudfoundry.identity.uaa.oauth.UaaAuthorizationEndpoint.java
private ModelAndView handleException(Exception e, ServletWebRequest webRequest) throws Exception { ResponseEntity<OAuth2Exception> translate = getExceptionTranslator().translate(e); webRequest.getResponse().setStatus(translate.getStatusCode().value()); if (e instanceof ClientAuthenticationException || e instanceof RedirectMismatchException) { Map<String, Object> map = new HashMap<>(); map.put("error", translate.getBody()); if (e instanceof UnauthorizedClientException) { map.put("error_message_code", "login.invalid_idp"); }//from www .ja v a 2 s . c o m return new ModelAndView(errorPage, map); } AuthorizationRequest authorizationRequest = null; try { authorizationRequest = getAuthorizationRequestForError(webRequest); String requestedRedirectParam = authorizationRequest.getRequestParameters() .get(OAuth2Utils.REDIRECT_URI); String requestedRedirect = redirectResolver.resolveRedirect(requestedRedirectParam, getClientServiceExtention().loadClientByClientId(authorizationRequest.getClientId(), IdentityZoneHolder.get().getId())); authorizationRequest.setRedirectUri(requestedRedirect); String redirect = getUnsuccessfulRedirect(authorizationRequest, translate.getBody(), authorizationRequest.getResponseTypes().contains("token")); return new ModelAndView(new RedirectView(redirect, false, true, false)); } catch (OAuth2Exception ex) { // If an AuthorizationRequest cannot be created from the incoming parameters it must be // an error. OAuth2Exception can be handled this way. Other exceptions will generate a standard 500 // response. return new ModelAndView(errorPage, Collections.singletonMap("error", translate.getBody())); } }
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); }//w w w. jav a 2 s . c o m 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.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;// w w w. ja 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.mitre.openid.connect.request.ConnectOAuth2RequestFactory.java
/** * @param inputParams//from w w w .j av a 2 s .c o m * @return */ private void processRequestObject(String jwtString, AuthorizationRequest request) { // parse the request object try { JWT jwt = JWTParser.parse(jwtString); if (jwt instanceof SignedJWT) { // it's a signed JWT, check the signature SignedJWT signedJwt = (SignedJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(signedJwt.getJWTClaimsSet().getStringClaim(CLIENT_ID)); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } JWSAlgorithm alg = signedJwt.getHeader().getAlgorithm(); if (client.getRequestObjectSigningAlg() == null || !client.getRequestObjectSigningAlg().equals(alg)) { throw new InvalidClientException("Client's registered request object signing algorithm (" + client.getRequestObjectSigningAlg() + ") does not match request object's actual algorithm (" + alg.getName() + ")"); } JWTSigningAndValidationService validator = validators.getValidator(client, alg); if (validator == null) { throw new InvalidClientException( "Unable to create signature validator for client " + client + " and algorithm " + alg); } if (!validator.validateSignature(signedJwt)) { throw new InvalidClientException( "Signature did not validate for presented JWT request object."); } } else if (jwt instanceof PlainJWT) { PlainJWT plainJwt = (PlainJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim(CLIENT_ID)); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } if (client.getRequestObjectSigningAlg() == null) { throw new InvalidClientException( "Client is not registered for unsigned request objects (no request_object_signing_alg registered)"); } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) { throw new InvalidClientException( "Client is not registered for unsigned request objects (request_object_signing_alg is " + client.getRequestObjectSigningAlg() + ")"); } // if we got here, we're OK, keep processing } else if (jwt instanceof EncryptedJWT) { EncryptedJWT encryptedJWT = (EncryptedJWT) jwt; // decrypt the jwt if we can encryptionService.decryptJwt(encryptedJWT); // TODO: what if the content is a signed JWT? (#525) if (!encryptedJWT.getState().equals(State.DECRYPTED)) { throw new InvalidClientException("Unable to decrypt the request object"); } // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim(CLIENT_ID)); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } } /* * NOTE: Claims inside the request object always take precedence over those in the parameter map. */ // now that we've got the JWT, and it's been parsed, validated, and/or decrypted, we can process the claims JWTClaimsSet claims = jwt.getJWTClaimsSet(); Set<String> responseTypes = OAuth2Utils.parseParameterList(claims.getStringClaim(RESPONSE_TYPE)); if (responseTypes != null && !responseTypes.isEmpty()) { if (!responseTypes.equals(request.getResponseTypes())) { logger.info( "Mismatch between request object and regular parameter for response_type, using request object"); } request.setResponseTypes(responseTypes); } String redirectUri = claims.getStringClaim(REDIRECT_URI); if (redirectUri != null) { if (!redirectUri.equals(request.getRedirectUri())) { logger.info( "Mismatch between request object and regular parameter for redirect_uri, using request object"); } request.setRedirectUri(redirectUri); } String state = claims.getStringClaim(STATE); if (state != null) { if (!state.equals(request.getState())) { logger.info( "Mismatch between request object and regular parameter for state, using request object"); } request.setState(state); } String nonce = claims.getStringClaim(NONCE); if (nonce != null) { if (!nonce.equals(request.getExtensions().get(NONCE))) { logger.info( "Mismatch between request object and regular parameter for nonce, using request object"); } request.getExtensions().put(NONCE, nonce); } String display = claims.getStringClaim(DISPLAY); if (display != null) { if (!display.equals(request.getExtensions().get(DISPLAY))) { logger.info( "Mismatch between request object and regular parameter for display, using request object"); } request.getExtensions().put(DISPLAY, display); } String prompt = claims.getStringClaim(PROMPT); if (prompt != null) { if (!prompt.equals(request.getExtensions().get(PROMPT))) { logger.info( "Mismatch between request object and regular parameter for prompt, using request object"); } request.getExtensions().put(PROMPT, prompt); } Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim(SCOPE)); if (scope != null && !scope.isEmpty()) { if (!scope.equals(request.getScope())) { logger.info( "Mismatch between request object and regular parameter for scope, using request object"); } request.setScope(scope); } JsonObject claimRequest = parseClaimRequest(claims.getStringClaim(CLAIMS)); if (claimRequest != null) { if (!claimRequest.equals(parseClaimRequest(request.getExtensions().get(CLAIMS).toString()))) { logger.info( "Mismatch between request object and regular parameter for claims, using request object"); } // we save the string because the object might not be a Java Serializable, and we can parse it easily enough anyway request.getExtensions().put(CLAIMS, claimRequest.toString()); } String loginHint = claims.getStringClaim(LOGIN_HINT); if (loginHint != null) { if (!loginHint.equals(request.getExtensions().get(LOGIN_HINT))) { logger.info( "Mistmatch between request object and regular parameter for login_hint, using requst object"); } request.getExtensions().put(LOGIN_HINT, loginHint); } } catch (ParseException e) { logger.error("ParseException while parsing RequestObject:", e); } }
From source file:org.mitre.openid.connect.ConnectOAuth2RequestFactory.java
/** * @param inputParams/* w w w . j a v a 2 s. c om*/ * @return */ private void processRequestObject(String jwtString, AuthorizationRequest request) { // parse the request object try { JWT jwt = JWTParser.parse(jwtString); // TODO: check parameter consistency, move keys to constants if (jwt instanceof SignedJWT) { // it's a signed JWT, check the signature SignedJWT signedJwt = (SignedJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(signedJwt.getJWTClaimsSet().getStringClaim("client_id")); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } JWSAlgorithm alg = signedJwt.getHeader().getAlgorithm(); if (client.getRequestObjectSigningAlg() != null) { if (!client.getRequestObjectSigningAlg().equals(alg)) { throw new InvalidClientException("Client's registered request object signing algorithm (" + client.getRequestObjectSigningAlg() + ") does not match request object's actual algorithm (" + alg.getName() + ")"); } } if (alg.equals(JWSAlgorithm.RS256) || alg.equals(JWSAlgorithm.RS384) || alg.equals(JWSAlgorithm.RS512)) { // it's RSA, need to find the JWK URI and fetch the key if (client.getJwksUri() == null) { throw new InvalidClientException( "Client must have a JWKS URI registered to use signed request objects."); } // check JWT signature JwtSigningAndValidationService validator = validators.getValidator(client.getJwksUri()); if (validator == null) { throw new InvalidClientException( "Unable to create signature validator for client's JWKS URI: " + client.getJwksUri()); } if (!validator.validateSignature(signedJwt)) { throw new InvalidClientException( "Signature did not validate for presented JWT request object."); } } else if (alg.equals(JWSAlgorithm.HS256) || alg.equals(JWSAlgorithm.HS384) || alg.equals(JWSAlgorithm.HS512)) { // it's HMAC, we need to make a validator based on the client secret JwtSigningAndValidationService validator = getSymmetricValidtor(client); if (validator == null) { throw new InvalidClientException( "Unable to create signature validator for client's secret: " + client.getClientSecret()); } if (!validator.validateSignature(signedJwt)) { throw new InvalidClientException( "Signature did not validate for presented JWT request object."); } } } else if (jwt instanceof PlainJWT) { PlainJWT plainJwt = (PlainJWT) jwt; // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(plainJwt.getJWTClaimsSet().getStringClaim("client_id")); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } if (client.getRequestObjectSigningAlg() == null) { throw new InvalidClientException( "Client is not registered for unsigned request objects (no request_object_signing_alg registered)"); } else if (!client.getRequestObjectSigningAlg().equals(Algorithm.NONE)) { throw new InvalidClientException( "Client is not registered for unsigned request objects (request_object_signing_alg is " + client.getRequestObjectSigningAlg() + ")"); } // if we got here, we're OK, keep processing } else if (jwt instanceof EncryptedJWT) { EncryptedJWT encryptedJWT = (EncryptedJWT) jwt; // decrypt the jwt if we can encryptionService.decryptJwt(encryptedJWT); if (!encryptedJWT.getState().equals(State.DECRYPTED)) { throw new InvalidClientException("Unable to decrypt the request object"); } // need to check clientId first so that we can load the client to check other fields if (request.getClientId() == null) { request.setClientId(encryptedJWT.getJWTClaimsSet().getStringClaim("client_id")); } ClientDetailsEntity client = clientDetailsService.loadClientByClientId(request.getClientId()); if (client == null) { throw new InvalidClientException("Client not found: " + request.getClientId()); } } /* * Claims precedence order logic: * * if (in Claims): * if (in params): * if (equal): * OK * else (not equal): * error * else (not in params): * add to params * else (not in claims): * we don't care */ // now that we've got the JWT, and it's been parsed, validated, and/or decrypted, we can process the claims ReadOnlyJWTClaimsSet claims = jwt.getJWTClaimsSet(); Set<String> responseTypes = OAuth2Utils.parseParameterList(claims.getStringClaim("response_type")); if (responseTypes != null && !responseTypes.isEmpty()) { if (request.getResponseTypes() == null || request.getResponseTypes().isEmpty()) { // if it's null or empty, we fill in the value with what we were passed request.setResponseTypes(responseTypes); } else if (!request.getResponseTypes().equals(responseTypes)) { // FIXME: throw an error } } String redirectUri = claims.getStringClaim("redirect_uri"); if (redirectUri != null) { if (request.getRedirectUri() == null) { request.setRedirectUri(redirectUri); } else if (!request.getRedirectUri().equals(redirectUri)) { // FIXME: throw an error } } String state = claims.getStringClaim("state"); if (state != null) { if (request.getState() == null) { request.setState(state); } else if (!request.getState().equals(state)) { // FIXME: throw an error } } String nonce = claims.getStringClaim("nonce"); if (nonce != null) { if (request.getExtensions().get("nonce") == null) { request.getExtensions().put("nonce", nonce); } else if (!request.getExtensions().get("nonce").equals(nonce)) { // FIXME: throw an error } } String display = claims.getStringClaim("display"); if (display != null) { if (request.getExtensions().get("display") == null) { request.getExtensions().put("display", display); } else if (!request.getExtensions().get("display").equals(display)) { // FIXME: throw an error } } String prompt = claims.getStringClaim("prompt"); if (prompt != null) { if (request.getExtensions().get("prompt") == null) { request.getExtensions().put("prompt", prompt); } else if (!request.getExtensions().get("prompt").equals(prompt)) { // FIXME: throw an error } } Set<String> scope = OAuth2Utils.parseParameterList(claims.getStringClaim("scope")); if (scope != null && !scope.isEmpty()) { if (request.getScope() == null || request.getScope().isEmpty()) { request.setScope(scope); } else if (!request.getScope().equals(scope)) { // FIXME: throw an error } } JsonObject claimRequest = parseClaimRequest(claims.getStringClaim("claims")); if (claimRequest != null) { if (request.getExtensions().get("claims") == null) { // we save the string because the object might not serialize request.getExtensions().put("claims", claimRequest.toString()); } else if (parseClaimRequest(request.getExtensions().get("claims").toString()) .equals(claimRequest)) { // FIXME: throw an error } } } catch (ParseException e) { logger.error("ParseException while parsing RequestObject:", e); } }
From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java
@Test public void testOpenIdTokenHybridFlowWithNoImplicitGrantWhenLenientWhenAppNotApproved() throws Exception { String clientId = "testclient" + generator.generate(); String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid"; setUpClients(clientId, scopes, scopes, "authorization_code", false); String username = "testuser" + generator.generate(); String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid"; ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZoneHolder.get().getId()); MockHttpSession session = getAuthenticatedSession(developer); String state = generator.generate(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setClientId(clientId); authorizationRequest.setRedirectUri(TEST_REDIRECT_URI); authorizationRequest.setScope(new ArrayList<>(Arrays.asList("openid"))); authorizationRequest.setResponseTypes(new TreeSet<>(Arrays.asList("code", "id_token"))); authorizationRequest.setState(state); session.setAttribute("authorizationRequest", authorizationRequest); MvcResult result = getMockMvc()//from www . j ava2 s . c o m .perform(post("/oauth/authorize").session(session).with(cookieCsrf()) .param(OAuth2Utils.USER_OAUTH_APPROVAL, "true").param("scope.0", "openid")) .andExpect(status().is3xxRedirection()).andReturn(); URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map query = splitQuery(url); assertNotNull(query.get("code")); String code = ((List<String>) query.get("code")).get(0); assertNotNull(code); }
From source file:org.cloudfoundry.identity.uaa.mock.token.TokenMvcMockTests.java
@Test public void testOpenIdTokenHybridFlowWithNoImplicitGrantWhenStrictWhenAppNotApproved() throws Exception { String clientId = "testclient" + generator.generate(); String scopes = "space.*.developer,space.*.admin,org.*.reader,org.123*.admin,*.*,*,openid"; setUpClients(clientId, scopes, scopes, "authorization_code", false); String username = "testuser" + generator.generate(); String userScopes = "space.1.developer,space.2.developer,org.1.reader,org.2.reader,org.12345.admin,scope.one,scope.two,scope.three,openid"; ScimUser developer = setUpUser(username, userScopes, OriginKeys.UAA, IdentityZoneHolder.get().getId()); MockHttpSession session = getAuthenticatedSession(developer); String state = generator.generate(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(); authorizationRequest.setClientId(clientId); authorizationRequest.setRedirectUri(TEST_REDIRECT_URI); authorizationRequest.setScope(new ArrayList<>(Arrays.asList("openid"))); authorizationRequest.setResponseTypes(new TreeSet<>(Arrays.asList("code", "id_token"))); authorizationRequest.setState(state); session.setAttribute("authorizationRequest", authorizationRequest); MvcResult result = getMockMvc()//from w ww. j a va2 s . co m .perform(post("/oauth/authorize").session(session).param(OAuth2Utils.USER_OAUTH_APPROVAL, "true") .with(cookieCsrf()).param("scope.0", "openid")) .andExpect(status().is3xxRedirection()).andReturn(); URL url = new URL(result.getResponse().getHeader("Location").replace("redirect#", "redirect?")); Map query = splitQuery(url); assertNotNull(query.get("id_token")); assertNotNull(((List) query.get("id_token")).get(0)); assertNotNull(((List) query.get("code")).get(0)); assertNull(query.get("token")); }
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 v a 2 s.co 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 handleException(Exception e, ServletWebRequest webRequest) throws Exception { ResponseEntity<OAuth2Exception> translate = getExceptionTranslator().translate(e); webRequest.getResponse().setStatus(translate.getStatusCode().value()); if (e instanceof ClientAuthenticationException || e instanceof RedirectMismatchException) { return new ModelAndView(errorPage, Collections.singletonMap("error", translate.getBody())); }/* w w w. j ava2 s. c om*/ AuthorizationRequest authorizationRequest = null; try { authorizationRequest = getAuthorizationRequestForError(webRequest); String requestedRedirectParam = authorizationRequest.getRequestParameters() .get(OAuth2Utils.REDIRECT_URI); String requestedRedirect = redirectResolver.resolveRedirect(requestedRedirectParam, getClientDetailsService().loadClientByClientId(authorizationRequest.getClientId())); authorizationRequest.setRedirectUri(requestedRedirect); String redirect = getUnsuccessfulRedirect(authorizationRequest, translate.getBody(), authorizationRequest.getResponseTypes().contains("token")); return new ModelAndView(new RedirectView(redirect, false, true, false)); } catch (OAuth2Exception ex) { // If an AuthorizationRequest cannot be created from the incoming parameters it must be // an error. OAuth2Exception can be handled this way. Other exceptions will generate a standard 500 // response. return new ModelAndView(errorPage, Collections.singletonMap("error", translate.getBody())); } }