List of usage examples for javax.servlet.http HttpServletResponse SC_FORBIDDEN
int SC_FORBIDDEN
To view the source code for javax.servlet.http HttpServletResponse SC_FORBIDDEN.
Click Source Link
From source file:net.shopxx.controller.admin.CommonController.java
/** * ??//w w w.j a v a 2 s .co m */ @RequestMapping("/admin/common/unauthorized") public String unauthorized(HttpServletRequest request, HttpServletResponse response) { String requestType = request.getHeader("X-Requested-With"); if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")) { response.addHeader("loginStatus", "unauthorized"); try { response.sendError(HttpServletResponse.SC_FORBIDDEN); } catch (IOException e) { e.printStackTrace(); } return null; } return "/admin/common/unauthorized"; }
From source file:net.bhira.sample.api.controller.DepartmentController.java
/** * Save the given instance of {@link net.bhira.sample.model.Department}. It will create a new * instance of the department does not exist, otherwise it will update the existing instance. * /* ww w . j a v a 2 s. c om*/ * @param request * the http request containing JSON payload in its body. * @param response * the http response to which the results will be written. * @return the error message, if save was not successful. */ @RequestMapping(value = "/department", method = RequestMethod.POST) @ResponseBody public Callable<String> saveDepartment(HttpServletRequest request, HttpServletResponse response) { return new Callable<String>() { public String call() throws Exception { String body = ""; try { LOG.debug("servicing POST department"); Gson gson = JsonUtil.createGson(); Department department = gson.fromJson(request.getReader(), Department.class); LOG.debug("POST department received json = {}", gson.toJson(department)); departmentService.save(department); HashMap<String, Long> map = new HashMap<String, Long>(); map.put("id", department.getId()); body = gson.toJson(map); LOG.debug("POST department/ successful with return ID = {}", department.getId()); } catch (Exception ex) { if (ex instanceof JsonSyntaxException) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); } body = ex.getLocalizedMessage(); LOG.warn("Error saving department. {}", body); LOG.debug("Save error stacktrace: ", ex); } return body; } }; }
From source file:net.shibboleth.idp.oidc.flow.BuildAuthorizationRequestContextAction.java
/** * Produce final event event./* w ww . j a va 2 s.c om*/ * * @param profileRequestContext the profile request context * @param response the response * @param authorizationRequest the authorization request * @param pairEvent the pair event * @param springRequestContext the spring request context * @param client the client details entity * @return the event */ private Event produceFinalEvent(final ProfileRequestContext profileRequestContext, final HttpServletResponse response, final OIDCAuthorizationRequestContext authorizationRequest, final Pair<Events, ? extends Object> pairEvent, final RequestContext springRequestContext, final ClientDetailsEntity client) { try { if (pairEvent.getFirst() == null) { log.error("Could not determine the final event based on authorization request"); return Events.BadRequest.event(this); } switch (pairEvent.getFirst()) { case Failure: log.error("Failed to process authorization request. Sending back response error"); response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied"); break; case Redirect: if (pairEvent.getSecond() != null) { log.debug("Authorization request indicated a redirect event to {}", pairEvent.getSecond()); final OIDCResponse oidcResponse = new OIDCResponse(); oidcResponse.setAuthorizationRequest(authorizationRequest.getAuthorizationRequest()); oidcResponse.setRedirectUri(pairEvent.getSecond().toString()); oidcResponse.setClient(client); OIDCUtils.putOIDCResponseIntoScope(oidcResponse, springRequestContext.getFlowScope()); } else { throw new OIDCException("No redirect url could be found based on the request"); } break; case Success: log.debug("Success. Proceeding with building the authorization context based on the request"); profileRequestContext.addSubcontext(authorizationRequest, true); break; default: log.debug("Proceeding to final event"); } final Event ev = pairEvent.getFirst().event(this); log.debug("Returning final event {}", ev.getId()); return ev; } catch (final Exception e) { log.error(e.getMessage(), e); throw new OIDCException(e); } }
From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java
/** * Communicates with redirect url and works as a transparent proxy * //from w ww. j a v a 2s.c om * @param request * the servlet request * @param response * the servlet response * @throws IOException * if an exception occurs */ private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpURLConnection httpCon = null; URL redirectURL = null; InputStream input = null; OutputStream output = null; InputStream proxyInput = null; OutputStream proxyOutput = null; try { input = request.getInputStream(); output = response.getOutputStream(); String sQueryStr = request.getQueryString(); String sAuthorization = request.getHeader("Authorization"); String requestBody = readInputCharacters(input); String requestMethod = request.getMethod(); String contentType = request.getContentType(); String encoding = request.getCharacterEncoding(); LOGGER.finer(" Request method = " + requestMethod); LOGGER.finer(" Query string = " + sQueryStr); LOGGER.finer(" Authorization header =" + sAuthorization); LOGGER.finer(" Character Encoding = " + encoding); LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr); redirectURL = new URL(this._redirectURL + "?" + sQueryStr); httpCon = (HttpURLConnection) redirectURL.openConnection(); httpCon.setDoInput(true); httpCon.setDoOutput(true); httpCon.setUseCaches(false); httpCon.setRequestMethod(requestMethod); httpCon.setRequestProperty("Content-type", contentType); if (sAuthorization != null) { httpCon.addRequestProperty("Authorization", sAuthorization); } proxyOutput = httpCon.getOutputStream(); send(requestBody, proxyOutput); String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate"); if (authenticateHdr != null) { LOGGER.finer(" WWW-Authenticate : " + authenticateHdr); response.setHeader("WWW-Authenticate", StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr))); } LOGGER.finer(" Response Code : " + httpCon.getResponseCode()); if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else { proxyInput = httpCon.getInputStream(); send(proxyInput, output); } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } if (proxyInput != null) { proxyInput.close(); } if (proxyOutput != null) { proxyOutput.close(); } if (httpCon != null) { httpCon.disconnect(); } } }
From source file:eu.dasish.annotation.backend.rest.CachedRepresentationResource.java
/** * //from w w w . ja va 2 s .com * @param externalId the external UUID of a cached representation. * @return the cached-representation's blob. * @throws IOException is sending an error fails. */ @GET //@Produces({"text/plain", "text/html", "text/xml", "application/zip", "image/png", "image/jpg"}) @Path("{cachedid: " + BackendConstants.regExpIdentifier + "}/stream") @Transactional(readOnly = true) public InputStream getCachedRepresentationContentStream(@PathParam("cachedid") String externalId) throws IOException { Map params = new HashMap(); try { return (InputStream) (new RequestWrappers(this)).wrapRequestResource(params, new GetCachedRepresentationInputStream(), Resource.CACHED_REPRESENTATION, Access.READ, externalId); } catch (NotInDataBaseException e1) { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND, e1.getMessage()); return null; } catch (ForbiddenException e2) { httpServletResponse.sendError(HttpServletResponse.SC_FORBIDDEN, e2.getMessage()); return null; } }
From source file:com.google.gerrit.httpd.auth.oauth.OAuthSession.java
private boolean authenticateWithIdentityClaimedDuringHandshake(AuthRequest req, HttpServletResponse rsp, String claimedIdentifier) throws AccountException, IOException { Optional<Account.Id> claimedId = accountManager.lookup(claimedIdentifier); Optional<Account.Id> actualId = accountManager.lookup(user.getExternalId()); if (claimedId.isPresent() && actualId.isPresent()) { if (claimedId.get().equals(actualId.get())) { // Both link to the same account, that's what we expected. log.debug("OAuth2: claimed identity equals current id"); } else {/* ww w . j av a 2 s . c o m*/ // This is (for now) a fatal error. There are two records // for what might be the same user. // log.error("OAuth accounts disagree over user identity:\n" + " Claimed ID: " + claimedId.get() + " is " + claimedIdentifier + "\n" + " Delgate ID: " + actualId.get() + " is " + user.getExternalId()); rsp.sendError(HttpServletResponse.SC_FORBIDDEN); return false; } } else if (claimedId.isPresent() && !actualId.isPresent()) { // Claimed account already exists: link to it. // log.info("OAuth2: linking claimed identity to {}", claimedId.get().toString()); try { accountManager.link(claimedId.get(), req); } catch (OrmException | ConfigInvalidException e) { log.error("Cannot link: " + user.getExternalId() + " to user identity:\n" + " Claimed ID: " + claimedId.get() + " is " + claimedIdentifier); rsp.sendError(HttpServletResponse.SC_FORBIDDEN); return false; } } return true; }
From source file:com.tasktop.c2c.server.webdav.server.SpringAwareWebdavServlet.java
@Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ITransaction transaction = null;/* w w w. j a va 2 s . co m*/ boolean needRollback = false; try { Principal userPrincipal = req.getUserPrincipal(); transaction = webdavStore.begin(userPrincipal); needRollback = true; webdavStore.checkAuthentication(transaction); IMethodExecutor methodExecutor = methodMap.get(req.getMethod()); if (methodExecutor == null) { methodExecutor = methodMap.get("*NO*IMPL*"); } methodExecutor.execute(transaction, req, resp); webdavStore.commit(transaction); needRollback = false; } catch (UnauthenticatedException e) { resp.sendError(WebdavStatus.SC_UNAUTHORIZED); } catch (AccessDeniedException ade) { // If we got a security exception, determine the correct type of error code to return. AuthenticationToken token = AuthenticationServiceUser.getCurrent().getToken(); List<String> roles = token.getAuthorities(); // Our request was rejected - time to send back an appropriate error. if (roles.contains(Role.Anonymous)) { // This was an anonymous request, so prompt the user for credentials - perhaps they can still do this. resp.addHeader("WWW-Authenticate", String.format("Basic realm=\"%s\"", TenancyUtil.getCurrentTenantProjectIdentifer())); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Please login to continue"); } else { // This user was authenticated, but this request is not allowed for permissions reasons - reject it. resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Insufficient permissions to perform this WebDav request"); } } catch (Exception e) { LOG.error(e); resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); throw new ServletException(e); } finally { if (needRollback) { webdavStore.rollback(transaction); } } }
From source file:com.netscape.cms.servlet.connector.ConnectorServlet.java
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean running_state = CMS.isInRunningState(); if (!running_state) throw new IOException("CMS server is not ready to serve."); HttpServletRequest req = request;/* w ww . j a va 2s. c o m*/ HttpServletResponse resp = response; CMSRequest cmsRequest = newCMSRequest(); // set argblock cmsRequest.setHttpParams(CMS.createArgBlock(toHashtable(request))); // set http request cmsRequest.setHttpReq(request); // set http response cmsRequest.setHttpResp(response); // set servlet config. cmsRequest.setServletConfig(mConfig); // set servlet context. cmsRequest.setServletContext(mConfig.getServletContext()); char[] content = null; String encodedreq = null; String method = null; int len = -1; IPKIMessage msg = null; IPKIMessage replymsg = null; // NOTE must read all bufer before redoing handshake for // ssl client auth for client auth to work. // get request method method = req.getMethod(); // get content length len = request.getContentLength(); // get content, a base 64 encoded serialized request. if (len > 0) { InputStream in = request.getInputStream(); InputStreamReader inreader = new InputStreamReader(in, "UTF8"); BufferedReader reader = new BufferedReader(inreader, len); content = new char[len]; int done = reader.read(content, 0, len); int total = done; while (done >= 0 && total < len) { done = reader.read(content, total, len - total); total += done; } reader.close(); encodedreq = new String(content); } // force client auth handshake, validate RA and get RA's Id. // NOTE must do this after all contents are read for ssl // redohandshake to work X509Certificate peerCert; try { peerCert = getPeerCert(req); } catch (EBaseException e) { mAuthority.log(ILogger.LL_SECURITY, CMS.getLogMessage("CMSGW_HAS_NO_CLIENT_CERT")); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } if (peerCert == null) { // XXX log something here. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // authenticate RA String RA_Id = null; String raUserId = null; IAuthToken token = null; try { token = authenticate(request); raUserId = token.getInString("userid"); RA_Id = peerCert.getSubjectDN().toString(); } catch (EInvalidCredentials e) { // already logged. resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } catch (EBaseException e) { // already logged. resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } mAuthority.log(ILogger.LL_INFO, "Remote Authority authenticated: " + peerCert.getSubjectDN()); // authorize AuthzToken authzToken = null; try { authzToken = authorize(mAclMethod, token, mAuthzResourceName, "submit"); } catch (Exception e) { // do nothing for now } if (authzToken == null) { cmsRequest.setStatus(ICMSRequest.UNAUTHORIZED); return; } // after cert validated, check http request. if (!method.equalsIgnoreCase("POST")) { resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } if (len <= 0) { resp.sendError(HttpServletResponse.SC_LENGTH_REQUIRED); return; } // now process request. CMS.debug("ConnectorServlet: process request RA_Id=" + RA_Id); try { // decode request. msg = (IPKIMessage) mReqEncoder.decode(encodedreq); // process request replymsg = processRequest(RA_Id, raUserId, msg, token); } catch (IOException e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString())); resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } catch (EBaseException e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); mAuthority.log(ILogger.LL_FAILURE, CMS.getLogMessage("CMSGW_IO_ERROR_REMOTE_REQUEST", e.toString())); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } catch (Exception e) { CMS.debug("ConnectorServlet: service " + e.toString()); CMS.debug(e); } CMS.debug("ConnectorServlet: done processRequest"); // encode reply try { String encodedrep = mReqEncoder.encode(replymsg); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/html"); resp.setContentLength(encodedrep.length()); // send reply OutputStream out = response.getOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(out, "UTF8"); writer.write(encodedrep); writer.flush(); writer.close(); out.flush(); } catch (Exception e) { CMS.debug("ConnectorServlet: error writing e=" + e.toString()); } CMS.debug("ConnectorServlet: send response RA_Id=" + RA_Id); }
From source file:org.apache.shindig.social.core.oauth2.OAuth2NormalizedRequest.java
private void normalizeClientSecret(HttpServletRequest request) throws OAuth2Exception { String secret = getClientSecret(); if (secret == null || secret.equals("")) { String header = request.getHeader("Authorization"); if (header != null && header.toLowerCase().startsWith("basic")) { String[] parts = header.split("[ \\t]+"); String temp = parts[parts.length - 1]; byte[] decodedSecret = Base64.decodeBase64(temp); try { temp = new String(decodedSecret, "UTF-8"); parts = temp.split(":"); if (parts != null && parts.length == 2) { secret = parts[1];//from ww w .j ava 2 s . co m String queryId = getString("client_id"); if (queryId != null && !queryId.equals(parts[0])) { OAuth2NormalizedResponse response = new OAuth2NormalizedResponse(); response.setError(ErrorType.INVALID_REQUEST.toString()); response.setErrorDescription("Request contains mismatched client ids"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); throw new OAuth2Exception(response); } // Lets set the client id from the Basic auth header if not already // set in query, // needed for client_credential flow. if (queryId == null) { put("client_id", parts[0]); } } } catch (UnsupportedEncodingException e) { LOG.logp(Level.WARNING, classname, "normalizeClientSecret", MessageKeys.INVALID_OAUTH, e); return; } } } put("client_secret", secret); }
From source file:ch.entwine.weblounge.common.impl.content.page.AbstractRenderer.java
/** * Convenience implementation for JSP renderer. The <code>renderer</code> url * is first looked up using the available language information from request * and site. Then it is included in the response. * /*from w ww . j a va 2 s.co m*/ * @param request * the request * @param response * the response * @param renderer * the renderer * @throws RenderException * if an error occurs while rendering */ protected void includeJSP(WebloungeRequest request, WebloungeResponse response, URL renderer) throws RenderException { Site site = request.getSite(); Language language = request.getLanguage(); File jsp = null; try { if ("file".equals(renderer.getProtocol())) { // Find the best match for the template String[] filePaths = LanguageUtils.getLanguageVariants(renderer.toExternalForm(), language, site.getDefaultLanguage()); for (String path : filePaths) { logger.trace("Looking for jsp {}", path); File f = new File(path); if (f.exists()) { logger.debug("Found jsp at {}", path); jsp = f; break; } } // Did we find a suitable JSP? if (jsp == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw new RenderException(this, "No suitable java server page found for " + renderer + " and language '" + language.getIdentifier() + "'"); } // Check readability if (!jsp.canRead()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); throw new RenderException(this, "Java server page at " + jsp + " cannot be read"); } // No directory listings allowed if (!jsp.isFile()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); throw new RenderException(this, "Java server page at " + jsp + " is not a file"); } renderer = jsp.toURI().toURL(); } // Prepare a request to site resources String servletPath = "/weblounge-sites/" + site.getIdentifier(); String requestPath = renderer.getPath(); requestPath = requestPath.substring(servletPath.length()); requestPath = UrlUtils.concat(Site.BUNDLE_PATH, requestPath); SiteRequestWrapper siteRequest = new SiteRequestWrapper(request, requestPath, false); RequestDispatcher dispatcher = request.getRequestDispatcher(servletPath); if (dispatcher == null) throw new IllegalStateException("No dispatcher found for site '" + site + "'"); // Finally serve the JSP logger.debug("Including jsp {}", renderer); dispatcher.include(siteRequest, response); response.getWriter().flush(); } catch (IOException e) { logger.error("Exception while including jsp {}", renderer, e); } catch (Throwable t) { throw new RenderException(this, t); } }