List of usage examples for javax.servlet.http HttpServletResponse SC_FOUND
int SC_FOUND
To view the source code for javax.servlet.http HttpServletResponse SC_FOUND.
Click Source Link
From source file:org.sakaiproject.blti.ProviderServlet.java
@SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String ipAddress = request.getRemoteAddr(); if (M_log.isDebugEnabled()) { M_log.debug("Basic LTI Provider request from IP=" + ipAddress); }/*w w w . jav a 2s. c om*/ String enabled = ServerConfigurationService.getString("basiclti.provider.enabled", null); if (enabled == null || !("true".equals(enabled))) { M_log.warn("Basic LTI Provider is Disabled IP=" + ipAddress); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Basic LTI Provider is Disabled"); return; } if (M_log.isDebugEnabled()) { Map<String, String[]> params = (Map<String, String[]>) request.getParameterMap(); for (Map.Entry<String, String[]> param : params.entrySet()) { M_log.debug(param.getKey() + ":" + param.getValue()[0]); } } Map payload = getPayloadAsMap(request); // Get the list of highly trusted consumers from sakai.properties. // If the incoming consumer is highly trusted, we use the context_id and // site_id as is, // ie without prefixing them with the oauth_consumer_key first. // We also don't both checking their roles in the site. boolean isTrustedConsumer = BasicLTIProviderUtil.isHighlyTrustedConsumer(payload); /* * Get the list of email trusted consumers from sakai.properties. If the * incoming consumer is email trusted, we use the email address provided * by the consumer and look up the "user" info from sakai instead of * consumer's. This use case is especially valuable if 2 different LMS's * acting as TP and TC referring to same user and can be uniquely * identified by email address. more details SAK-29372 */ boolean isEmailTrustedConsumer = BasicLTIProviderUtil.isEmailTrustedConsumer(payload); /* * Checking if the email trusted consumer property and trusted consumer * and not both enabled. the case would be an error condition */ if (isTrustedConsumer && isEmailTrustedConsumer) { M_log.warn("Both Email Trusted and Trusted Consumer property is enabled, this is invalid IP=" + ipAddress); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Both Email Trusted and Trusted Consumer property is enabled, this is invalid "); return; } try { invokeProcessors(payload, isTrustedConsumer, ProcessingState.beforeValidation); validate(payload, isTrustedConsumer); invokeProcessors(payload, isTrustedConsumer, ProcessingState.afterValidation); User user = userFinderOrCreator.findOrCreateUser(payload, isTrustedConsumer, isEmailTrustedConsumer); invokeProcessors(payload, isTrustedConsumer, ProcessingState.afterUserCreation, user); loginUser(ipAddress, user); invokeProcessors(payload, isTrustedConsumer, ProcessingState.afterLogin, user); // This needs to happen after login, when we have a session for the user. userLocaleSetter.setupUserLocale(payload, user, isTrustedConsumer, isEmailTrustedConsumer); userPictureSetter.setupUserPicture(payload, user, isTrustedConsumer, isEmailTrustedConsumer); Site site = findOrCreateSite(payload, isTrustedConsumer); invokeProcessors(payload, isTrustedConsumer, ProcessingState.afterSiteCreation, user, site); siteEmailPreferenceSetter.setupUserEmailPreferenceForSite(payload, user, site, isTrustedConsumer); site = siteMembershipUpdater.addOrUpdateSiteMembership(payload, isTrustedConsumer, user, site); invokeProcessors(payload, isTrustedConsumer, ProcessingState.afterSiteMembership, user, site); String toolPlacementId = addOrCreateTool(payload, isTrustedConsumer, user, site); invokeProcessors(payload, isTrustedConsumer, ProcessingState.beforeLaunch, user, site); syncSiteMembershipsOnceThenSchedule(payload, site, isTrustedConsumer, isEmailTrustedConsumer); // Construct a URL to this tool StringBuilder url = new StringBuilder(); url.append(ServerConfigurationService.getServerUrl()); url.append(ServerConfigurationService.getString("portalPath", "/portal")); url.append("/tool-reset/"); url.append(toolPlacementId); url.append("?panel=Main"); if (M_log.isDebugEnabled()) { M_log.debug("url=" + url.toString()); } //String toolLink = ServerConfigurationService.getPortalUrl()+ "/tool-reset/" + placement_id + "?panel=Main"; // Compensate for bug in getPortalUrl() //toolLink = toolLink.replace("IMS BLTI Portlet", "portal"); response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_FOUND); response.sendRedirect(url.toString()); } catch (LTIException ltiException) { doError(request, response, ltiException.getErrorKey(), ltiException.getMessage(), ltiException.getCause()); } /* PrintWriter out = response.getWriter(); out.println("<body><div style=\"text-align: center\">"); out.println(" <br/> <br/> <br/> <br/>"); out.println(" <br/> <br/> <br/> <br/>"); out.println("<a href=\"" + url.toString() + "\">"); out.println("<span id=\"hideme\">" + rb.getString("launch.continue") + "</span>"); out.println("</a>"); out.println(" <script language=\"javascript\"> \n" + " document.getElementById(\"hideme\").style.display = \"none\";\n" + " location.href=\"" + url.toString() + "\";\n" + " </script> \n"); out.println("</div>"); out.println("</body>"); out.close(); */ }
From source file:edu.harvard.i2b2.fhir.oauth2.ws.OAuth2AuthzEndpoint.java
String successfulResponse(HttpServletRequest request)//, String scope, String patientId, String state) throws OAuthSystemException, URISyntaxException, OAuthProblemException { OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request); OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator()); String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE); OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND); String redirectURI = oauthRequest.getRedirectURI(); if (responseType.equals(ResponseType.CODE.toString())) { String authorizationCode = oauthIssuerImpl.authorizationCode(); logger.info("generated authorizationCode:" + authorizationCode); builder.setCode(authorizationCode); HttpSession session = request.getSession(); session.setAttribute("authorizationCode", authorizationCode); logger.info("put generated authcode " + session.getAttribute("authorizationCode") + " in session " + session.getId());//from w w w. j a v a 2 s . c o m } URI fhirBase = HttpHelper.getBasePath(request, serverConfigs); String uri = fhirBase.toString(); uri = uri.substring(0, uri.length() - 1);//chopping of last / uri = uri.substring(0, uri.lastIndexOf('/')) + "/"; OAuthResponse Oresponse = builder.location(redirectURI).setParam("aud", uri).buildQueryMessage(); URI url = new URI(Oresponse.getLocationUri()); return url.toString(); }
From source file:com.mercer.cpsg.swarm.oidc.deployment.OIDCAuthenticationMechanism.java
protected AuthenticationMechanismOutcome complete(JWTClaimsSet claims, AccessToken accessToken, String returnURL, HttpServerExchange exchange, boolean redirect) throws Exception { OIDCPrincipal principal = new OIDCPrincipalExt(claims, accessToken); Account account = new AccountImpl(principal); account = identityManager.verify(account); if (account == null) { LOG.warning(String.format("OIDC subject %s not found in identity manager", principal.getName())); exchange.getSecurityContext().authenticationFailed("OIDC subject not found in identity manager", mechanismName);/*from w w w. j av a 2 s .c o m*/ OIDCContext oidcContext = exchange.getAttachment(OIDCContext.ATTACHMENT_KEY); oidcContext.setError(true); return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } exchange.getSecurityContext().authenticationComplete(account, mechanismName, true); if (redirect) { exchange.getResponseHeaders().put(Headers.LOCATION, returnURL != null && !returnURL.isEmpty() ? returnURL : "/"); exchange.setStatusCode(HttpServletResponse.SC_FOUND); exchange.endExchange(); } LOG.fine("authentificated " + principal); return AuthenticationMechanismOutcome.AUTHENTICATED; }
From source file:org.openmhealth.reference.servlet.Version1.java
/** * <p>//from w w w. j a v a2s. c o m * The OAuth call where a user has been redirected to us by some * third-party in order for us to present them with an authorization * request, verify that the user is who they say they are, and grant or * deny the request. * </p> * * <p> * This call will either redirect the user to the authorization HTML page * with the parameters embedded or it will return a non-2xx response with a * message indicating what was wrong with the request. Unfortunately, * because the problem with the request may be that the given client ID is * unknown, we have no way to direct the user back. If we simply force the * browser to "go back", it may result in an infinite loop where the * third-party continuously redirects them back to us and visa-versa. To * avoid this, we should simply return an error string and let the user * decide. * </p> * * @param request * The HTTP request. * * @param response * The HTTP response. * * @return A OAuth-specified JSON response that indicates what was wrong * with the request. If nothing was wrong with the request, a * redirect would have been returned. * * @throws IOException * There was a problem responding to the client. * * @throws OAuthSystemException * The OAuth library encountered an error. */ @RequestMapping(value = "auth/oauth/authorize", method = { RequestMethod.GET, RequestMethod.POST }) public @ResponseBody String receiveAuthorizationCodeRequest(final HttpServletRequest request, final HttpServletResponse response) throws IOException, OAuthSystemException { // Create the OAuth request from the HTTP request. OAuthAuthzRequest oauthRequest; try { oauthRequest = new OAuthAuthzRequest(request); } // The request does not conform to the RFC, so we return a HTTP 400 // with a reason. catch (OAuthProblemException e) { // Create the OAuth response. OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST).error(e) .buildJSONMessage(); // Set the status and return the error message. response.setStatus(oauthResponse.getResponseStatus()); return oauthResponse.getBody(); } // Validate that the user is requesting a "code" response type, which // is the only response type we accept. try { if (!ResponseType.CODE.toString().equals(oauthRequest.getResponseType())) { // Create the OAuth response. OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST) .setError(CodeResponse.UNSUPPORTED_RESPONSE_TYPE) .setErrorDescription("The response type must be '" + ResponseType.CODE.toString() + "' but was instead: " + oauthRequest.getResponseType()) .setState(oauthRequest.getState()).buildJSONMessage(); // Set the status and return the error message. response.setStatus(oauthResponse.getResponseStatus()); return oauthResponse.getBody(); } } catch (IllegalArgumentException e) { // Create the OAuth response. OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST) .setError(CodeResponse.UNSUPPORTED_RESPONSE_TYPE) .setErrorDescription("The response type is unknown: " + oauthRequest.getResponseType()) .setState(oauthRequest.getState()).buildJSONMessage(); // Set the status and return the error message. response.setStatus(oauthResponse.getResponseStatus()); return oauthResponse.getBody(); } // Make sure no redirect URI was given. if (oauthRequest.getRedirectURI() != null) { // Create the OAuth response. OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST) .setError(CodeResponse.INVALID_REQUEST) .setErrorDescription("A URI must not be given. Instead, the one given " + "when the account was created will be used.") .setState(oauthRequest.getState()).buildJSONMessage(); // Set the status and return the error message. response.setStatus(oauthResponse.getResponseStatus()); return oauthResponse.getBody(); } // Attempt to get the third-party. ThirdParty thirdParty = ThirdPartyBin.getInstance().getThirdParty(oauthRequest.getClientId()); // If the third-party is unknown, reject the request. if (thirdParty == null) { // Create the OAuth response. OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST) .setError(CodeResponse.INVALID_REQUEST) .setErrorDescription("The client ID is unknown: " + oauthRequest.getClientId()) .setState(oauthRequest.getState()).buildJSONMessage(); // Set the status and return the error message. response.setStatus(oauthResponse.getResponseStatus()); return oauthResponse.getBody(); } // Attempt to get the scopes. Set<String> scopes = oauthRequest.getScopes(); if ((scopes == null) || (scopes.size() == 0)) { // Create the OAuth response. OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST) .setError(CodeResponse.INVALID_SCOPE).setErrorDescription("A scope is required.") .setState(oauthRequest.getState()).buildJSONMessage(); // Set the status and return the error message. response.setStatus(oauthResponse.getResponseStatus()); return oauthResponse.getBody(); } // Validate the scopes. Registry registry = Registry.getInstance(); for (String scope : scopes) { if (registry.getSchemas(scope, null, 0, 1).size() != 1) { // Create the OAuth response. OAuthResponse oauthResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST) .setError(CodeResponse.INVALID_SCOPE) .setErrorDescription("Each scope must be a known schema ID: " + scope) .setState(oauthRequest.getState()).buildJSONMessage(); // Set the status and return the error message. response.setStatus(oauthResponse.getResponseStatus()); return oauthResponse.getBody(); } } // Create the temporary code to be granted or rejected by the user. AuthorizationCode code = new AuthorizationCode(thirdParty, oauthRequest.getScopes(), oauthRequest.getState()); // Store the authorization code. AuthorizationCodeBin.getInstance().storeCode(code); // Build the scope as specified by the OAuth specification. StringBuilder scopeBuilder = new StringBuilder(); for (String scope : code.getScopes()) { // Add a space unless it's the first entity. if (scopeBuilder.length() != 0) { scopeBuilder.append(' '); } // Add the scope. scopeBuilder.append(scope); } // Set the redirect. response.sendRedirect(OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND) .setCode(code.getCode()).location("Authorize.html").setScope(scopeBuilder.toString()) .setParam(ThirdParty.JSON_KEY_NAME, thirdParty.getName()) .setParam(ThirdParty.JSON_KEY_DESCRIPTION, thirdParty.getDescription()).buildQueryMessage() .getLocationUri()); // Since we are redirecting the user, we don't need to return anything. return null; }
From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpointTest.java
@DataProvider(name = "provideAuthenticatedData") public Object[][] provideAuthenticatedData() { return new Object[][] { { true, true, new HashMap(), null, null, null, new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), RESPONSE_MODE_FORM_POST, APP_REDIRECT_URL, HttpServletResponse.SC_FOUND }, { false, true, null, null, null, null, new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), RESPONSE_MODE_FORM_POST, APP_REDIRECT_URL, HttpServletResponse.SC_FOUND }, { true, true, new HashMap(), null, null, null, new HashSet<>(Arrays.asList("scope1")), "not_form_post", APP_REDIRECT_URL, HttpServletResponse.SC_FOUND }, { true, true, new HashMap(), null, null, null, new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), RESPONSE_MODE_FORM_POST, APP_REDIRECT_URL_JSON, HttpServletResponse.SC_OK }, { true, true, new HashMap(), null, null, null, new HashSet<>(Arrays.asList("scope1")), RESPONSE_MODE_FORM_POST, APP_REDIRECT_URL_JSON, HttpServletResponse.SC_OK }, { true, false, null, OAuth2ErrorCodes.INVALID_REQUEST, null, null, new HashSet<>(Arrays.asList("scope1")), RESPONSE_MODE_FORM_POST, APP_REDIRECT_URL, HttpServletResponse.SC_OK }, { true, false, null, null, "Error!", null, new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), RESPONSE_MODE_FORM_POST, APP_REDIRECT_URL, HttpServletResponse.SC_OK }, { true, false, null, null, null, "http://localhost:8080/error", new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), RESPONSE_MODE_FORM_POST, APP_REDIRECT_URL, HttpServletResponse.SC_OK } }; }
From source file:cn.vlabs.umt.ui.servlet.AuthorizationCodeServlet.java
/** * ?responseTypecode/*from ww w . j av a 2 s. co m*/ * @param request * @param response * @param oauthRequest * @throws IOException * @throws ServletException */ private void responseTypeIsCode(HttpServletRequest request, HttpServletResponse response, OAuthAuthzRequestWrap oauthRequest) throws IOException, ServletException { String[] scopses = request.getParameterValues("userScopes"); String redirectURI = getRedirectURI(request, oauthRequest); OAuthResponse resp; try { LoginInfo userLogin = UMTContext.getLoginInfo(request.getSession()); AuthorizationCodeBean bean = createAuthCodeBean(userLogin, oauthRequest); bean.updateScope(scopses); // bean.setExpiredTime(new Date(System.currentTimeMillis() + authorTimeout * 60l * 1000l)); getCodeServer().save(bean); resp = OAuthASResponse.authorizationResponse(request, HttpServletResponse.SC_FOUND) .setCode(bean.getCode()).setParam("state", bean.getState()).location(redirectURI) .buildQueryMessage(); response.sendRedirect(resp.getLocationUri()); } catch (OAuthSystemException e) { dealOAuthSystemError(redirectURI, e, request, response); } }
From source file:edu.stanford.epad.plugins.qifpwrapper.QIFPHandler.java
private static EPADSessionResponse getEPADSessionID(String username, String password, String epadHost, int port) { String epadSessionURL = buildEPADSessionURL(epadHost, port); HttpClient client = new HttpClient(); PostMethod method = new PostMethod(epadSessionURL); String authString = buildAuthorizationString(username, password); EPADSessionResponse epadSessionResponse; int epadStatusCode; try {/*from w w w .j a v a2s . co m*/ log.info("Invoking EPAD session service for user " + username + " at " + epadSessionURL); method.setRequestHeader("Authorization", "Basic " + authString); epadStatusCode = client.executeMethod(method); log.info("Successfully invoked EPAD session service for user " + username + "; status code = " + epadStatusCode); } catch (IOException e) { log.warning("Error calling EPAD session service for user " + username, e); epadStatusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; } try { if (epadStatusCode == HttpServletResponse.SC_OK || epadStatusCode == HttpServletResponse.SC_FOUND) { try { StringBuilder sb = new StringBuilder(); InputStreamReader isr = null; try { isr = new InputStreamReader(method.getResponseBodyAsStream()); int read = 0; char[] chars = new char[128]; while ((read = isr.read(chars)) > 0) { sb.append(chars, 0, read); } } finally { IOUtils.closeQuietly(isr); } String jsessionID = sb.toString(); epadSessionResponse = new EPADSessionResponse(HttpServletResponse.SC_OK, jsessionID, ""); log.debug("Session ID " + jsessionID + " generated for user " + username); // TODO temp } catch (IOException e) { log.warning(LOGIN_EXCEPTION_MESSAGE, e); epadSessionResponse = new EPADSessionResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, LOGIN_EXCEPTION_MESSAGE + ": " + e.getMessage()); } } else if (epadStatusCode == HttpServletResponse.SC_UNAUTHORIZED) { log.warning(EPAD_UNAUTHORIZED_MESSAGE); epadSessionResponse = new EPADSessionResponse(epadStatusCode, null, EPAD_UNAUTHORIZED_MESSAGE); } else { log.warning(EPAD_LOGIN_ERROR_MESSAGE + "; EPAD status code = " + epadStatusCode); epadSessionResponse = new EPADSessionResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, EPAD_LOGIN_ERROR_MESSAGE + "; EPAD status code = " + epadStatusCode); } } finally { method.releaseConnection(); } return epadSessionResponse; }
From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpointTest.java
@DataProvider(name = "provideConsentData") public Object[][] provideConsentData() { return new Object[][] { { null, APP_REDIRECT_URL, new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), HttpServletResponse.SC_FOUND, OAuth2ErrorCodes.INVALID_REQUEST }, { "deny", APP_REDIRECT_URL, new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), HttpServletResponse.SC_OK, OAuth2ErrorCodes.ACCESS_DENIED }, { "deny", APP_REDIRECT_URL, new HashSet<>(Arrays.asList("scope1")), HttpServletResponse.SC_OK, OAuth2ErrorCodes.ACCESS_DENIED }, { "approve", APP_REDIRECT_URL, new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), HttpServletResponse.SC_FOUND, null }, { "approve", APP_REDIRECT_URL, new HashSet<>(Arrays.asList("scope1")), HttpServletResponse.SC_FOUND, null },/*from ww w .jav a 2 s . c om*/ { "approve", APP_REDIRECT_URL_JSON, new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), HttpServletResponse.SC_OK, null }, { "approve", APP_REDIRECT_URL_JSON, new HashSet<>(Arrays.asList("scope1")), HttpServletResponse.SC_OK, null }, }; }
From source file:cn.vlabs.umt.ui.servlet.AuthorizationCodeServlet.java
private void dealOAuthSystemError(String redirectURI, OAuthSystemException e, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (StringUtils.isEmpty(redirectURI)) { request.setAttribute("client_id", request.getParameter("client_id")); request.setAttribute("errorCode", "server_error"); request.setAttribute("errorDescription", e.getMessage()); dealClientRedirectError(request, response); return;//from w ww . j a va 2s.co m } OAuthResponse resp = null; try { resp = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).setError("server_error") .location(redirectURI).buildQueryMessage(); } catch (OAuthSystemException ex) { LOG.error("redirectURI=" + redirectURI, ex); } LOG.error("", e); response.sendRedirect(resp.getLocationUri()); }