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:pt.webdetails.cpf.SimpleContentGenerator.java
protected boolean invokeMethod(final String methodName, final Method method) throws InvocationTargetException, IllegalArgumentException, IllegalAccessException, IOException { Exposed exposed = method.getAnnotation(Exposed.class); if (canAccessMethod(method, exposed)) { Audited audited = method.getAnnotation(Audited.class); UUID uuid = null;/*from w w w . j a v a2 s . c o m*/ long start = System.currentTimeMillis(); if (audited != null) { uuid = CpfAuditHelper.startAudit(getPluginName(), audited.action(), getObjectName(), userSession, this, getRequestParameters()); } final OutputStream out = getResponseOutputStream(exposed.outputType()); setResponseHeaders(exposed.outputType()); try { method.invoke(this, out); } finally { if (audited != null) { CpfAuditHelper.endAudit(getPluginName(), audited.action(), getObjectName(), userSession, this, start, uuid, System.currentTimeMillis()); } } return true; } String msg = "Method " + methodName + " not exposed or user does not have required permissions."; logger.error(msg); getResponse().sendError(HttpServletResponse.SC_FORBIDDEN, msg); return false; }
From source file:it.greenvulcano.gvesb.adapter.http.mapping.RESTHttpServletMapping.java
/** * @param req//from w w w . j av a 2 s.c o m * @param resp * @return if request handling was successful * @throws InboundHttpResponseException */ public void handleRequest(String methodName, HttpServletRequest req, HttpServletResponse resp) throws InboundHttpResponseException { logger.debug("handleRequest start"); long startTime = System.currentTimeMillis(); GVTransactionInfo transInfo = new GVTransactionInfo(); Throwable exception = null; GVBuffer response = null; try { if (dump) { StringBuffer sb = new StringBuffer(); DumpUtils.dump(req, sb); logger.info(sb.toString()); } String path = req.getPathInfo(); if (path == null) { path = "/"; } String query = req.getQueryString(); if (query == null) { query = ""; } GVBuffer request = new GVBuffer(); String operationType = null; PatternResolver pr = null; Iterator<PatternResolver> i = operationMappings.iterator(); while (i.hasNext()) { pr = i.next(); operationType = pr.match(req, methodName, path, request); if (operationType != null) { break; } } if (operationType == null) { logger.error(action + " - handleRequest - Error while handling request parameters: unable to decode requested operation [" + methodName + "#" + path + "]"); resp.sendError(400, "Unable to decode the requested operation [" + methodName + "#" + path + "]"); } transInfo.setService(request.getService()); transInfo.setSystem(request.getSystem()); transInfo.setId(request.getId()); transInfo.setOperation(operationType); request.setProperty("HTTP_ACTION", action); request.setProperty("HTTP_PATH", path); request.setProperty("HTTP_QUERY", query); request.setProperty("HTTP_METHOD", methodName); // get remote transport address... String remAddr = req.getRemoteAddr(); request.setProperty("HTTP_REMOTE_ADDR", (remAddr != null ? remAddr : "")); parseRequest(req, methodName, pr, request); GVBufferMDC.put(request); NMDC.setOperation(operationType); logger.info(GVFormatLog.formatBEGINOperation(request).toString()); transactionManager.begin(request.getService(), operationType); response = executeService(operationType, request); if (response.getPropertyNamesSet().contains("HTTP_FORCE_TX_ROLLBACK")) { transInfo.setErrorCode(-1); } else { transactionManager.commit(transInfo, true); manageHttpResponse(response, resp); transactionManager.commit(transInfo, false); } logger.debug("handleRequest stop"); } catch (Throwable exc) { exception = exc; transInfo.setErrorCode(-1); logger.error("handleRequest - Service request failed", exc); try { if (exc.getMessage().contains("GV_SERVICE_POLICY_ERROR")) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); } else { resp.sendError(500, "" + exc); } } catch (IOException exc1) { throw new InboundHttpResponseException("GVHTTP_INBOUND_HTTP_RESPONSE_ERROR", new String[][] { { "errorName", "" + exc1 } }, exc1); } } finally { if (transInfo.isError()) { try { transactionManager.rollback(transInfo, false); } catch (Exception exc) { logger.error("handleRequest - Transaction failed: " + exc); } } long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; GVFormatLog gvFormatLog = null; if (exception != null) { gvFormatLog = GVFormatLog.formatENDOperation(exception, totalTime); } else { if (response != null) { gvFormatLog = GVFormatLog.formatENDOperation(response, totalTime); } else { gvFormatLog = GVFormatLog.formatENDOperation(totalTime); } } logger.info(gvFormatLog.toString()); } }
From source file:com.sonicle.webtop.core.app.servlet.ResourceRequest.java
private LookupResult lookupLoginImage(HttpServletRequest request, URL targetUrl) { String targetPath = targetUrl.getPath(); URL fileUrl = null;//from w ww .jav a 2 s.c om try { WebTopApp wta = WebTopApp.get(request); //String internetName = ServletUtils.getInternetName(request); String internetName = ServletUtils.getHost(request); String domainId = WT.findDomainIdByInternetName(internetName); if (!StringUtils.isBlank(domainId)) { String pathname = wta.getImagesPath(domainId) + "login.png"; File file = new File(pathname); if (file.exists()) { fileUrl = file.toURI().toURL(); } } if (fileUrl == null) { fileUrl = getResURL(targetPath); } Resource resFile = getFile(wta, fileUrl); StaticFile sf = new StaticFile(fileUrl.toString(), getMimeType(targetPath), ClientCaching.NO, resFile); sf.cacheLastModified = false; return sf; } catch (ForbiddenException ex) { return new Error(HttpServletResponse.SC_FORBIDDEN, "Forbidden"); } catch (MalformedURLException | NotFoundException ex) { return new Error(HttpServletResponse.SC_NOT_FOUND, "Not Found"); } catch (InternalServerException ex) { return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } catch (ServletException ex) { return new Error(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex.getMessage()); } }
From source file:bbdn.lti2.LTI2Servlet.java
@SuppressWarnings({ "unchecked", "unused", "rawtypes" }) public void registerToolProviderProfile(HttpServletRequest request, HttpServletResponse response, String profile_id) throws java.io.IOException { // Normally we would look up the deployment descriptor if (!"42".equals(profile_id)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return;/* w ww . ja v a 2s. co m*/ } String key = "42"; String secret = "zaphod"; IMSJSONRequest jsonRequest = new IMSJSONRequest(request); if (!jsonRequest.valid) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "Request is not in a valid format", null); return; } System.out.println(jsonRequest.getPostBody()); // Lets check the signature if (key == null || secret == null) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, "Deployment is missing credentials", null); return; } jsonRequest.validateRequest(key, secret, request); if (!jsonRequest.valid) { response.setStatus(HttpServletResponse.SC_FORBIDDEN); doErrorJSON(request, response, jsonRequest, "OAuth signature failure", null); return; } JSONObject providerProfile = (JSONObject) JSONValue.parse(jsonRequest.getPostBody()); // System.out.println("OBJ:"+providerProfile); if (providerProfile == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "JSON parse failed", null); return; } JSONObject default_custom = (JSONObject) providerProfile.get(LTI2Constants.CUSTOM); JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT); if (security_contract == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "JSON missing security_contract", null); return; } String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET); System.out.println("shared_secret=" + shared_secret); if (shared_secret == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, "JSON missing shared_secret", null); return; } // Make sure that the requested services are a subset of the offered services ToolConsumer consumer = buildToolConsumerProfile(request, null, profile_id); JSONArray tool_services = (JSONArray) security_contract.get(LTI2Constants.TOOL_SERVICE); String retval = LTI2Util.validateServices(consumer, providerProfile); if (retval != null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, retval, null); return; } // Parse the tool profile bit and extract the tools with error checking retval = LTI2Util.validateCapabilities(consumer, providerProfile); if (retval != null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); doErrorJSON(request, response, jsonRequest, retval, null); return; } // Pass the profile to the launch process PERSIST.put("profile", providerProfile.toString()); // Share our happiness with the Tool Provider Map jsonResponse = new TreeMap(); jsonResponse.put(LTI2Constants.CONTEXT, StandardServices.TOOLPROXY_ID_CONTEXT); jsonResponse.put(LTI2Constants.TYPE, StandardServices.TOOLPROXY_ID_TYPE); jsonResponse.put(LTI2Constants.JSONLD_ID, getServiceURL(request) + SVC_tc_registration + "/" + profile_id); jsonResponse.put(LTI2Constants.TOOL_PROXY_GUID, profile_id); jsonResponse.put(LTI2Constants.CUSTOM_URL, getServiceURL(request) + SVC_Settings + "/" + LTI2Util.SCOPE_ToolProxy + "/" + profile_id); response.setContentType(StandardServices.TOOLPROXY_ID_FORMAT); response.setStatus(HttpServletResponse.SC_CREATED); String jsonText = JSONValue.toJSONString(jsonResponse); M_log.debug(jsonText); PrintWriter out = response.getWriter(); out.println(jsonText); }
From source file:com.alfaariss.oa.profile.saml2.profile.sso.WebBrowserSSO.java
/** * @see ISAML2Profile#process(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) *///from w w w. ja v a2 s . c o m public void process(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException { ISession session = null; try { String sSessionId = servletRequest.getParameter(ISession.ID_NAME); if (sSessionId != null) { if (!SessionValidator.validateDefaultSessionId(sSessionId)) { _logger.warn("Invalid session id in request: " + sSessionId); throw new UserException(UserEvent.REQUEST_INVALID); } session = _sessionFactory.retrieve(sSessionId); if (session == null) { StringBuffer sbError = new StringBuffer("No session with id '"); sbError.append(sSessionId); sbError.append("' found in request sent from IP: "); sbError.append(servletRequest.getRemoteAddr()); _logger.debug(sbError.toString()); throw new UserException(UserEvent.REQUEST_INVALID); } if (session.isExpired()) { StringBuffer sbError = new StringBuffer("Expired session with id '"); sbError.append(sSessionId); sbError.append("' found in request sent from IP: "); sbError.append(servletRequest.getRemoteAddr()); _logger.debug(sbError.toString()); throw new UserException(UserEvent.REQUEST_INVALID); } processAuthenticationResponse(servletRequest, servletResponse, session); } else processSAMLRequest(servletRequest, servletResponse, session); } catch (UserException e) //User error { UserEventLogItem logItem = null; if (session != null) logItem = new UserEventLogItem(session, servletRequest.getRemoteAddr(), e.getEvent(), this, null); else logItem = new UserEventLogItem(null, null, null, e.getEvent(), null, servletRequest.getRemoteAddr(), null, this, null); _eventLogger.info(logItem); if (!servletResponse.isCommitted()) { try { servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST); } catch (IOException e1) { _logger.warn("Could not send response", e1); } } } catch (SAML2SecurityException e) { //DD Security error -> Return a "403 Forbidden" response _logger.debug("Security error", e); _eventLogger.info(new RequestorEventLogItem(null, null, null, e.getEvent(), null, servletRequest.getRemoteAddr(), null, this, "Security Fault")); try { if (!servletResponse.isCommitted()) servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN); } catch (IOException e1) { _logger.warn("Could not send response", e1); } } catch (OAException e) { RequestorEventLogItem oLogItem = null; if (session != null) oLogItem = new RequestorEventLogItem(session, servletRequest.getRemoteAddr(), RequestorEvent.REQUEST_INVALID, this, null); else oLogItem = new RequestorEventLogItem(null, null, null, RequestorEvent.REQUEST_INVALID, null, servletRequest.getRemoteAddr(), null, this, null); _eventLogger.info(oLogItem); throw e; } catch (Exception e) { RequestorEventLogItem oLogItem = null; if (session != null) oLogItem = new RequestorEventLogItem(session, servletRequest.getRemoteAddr(), RequestorEvent.INTERNAL_ERROR, this, null); else oLogItem = new RequestorEventLogItem(null, null, null, RequestorEvent.INTERNAL_ERROR, null, servletRequest.getRemoteAddr(), null, this, null); _eventLogger.info(oLogItem); _logger.fatal("Internal error during process", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } }
From source file:elw.web.StudentController.java
private boolean accessDenied(HttpServletResponse resp, Ctx ctx, String scope, FileSlot slot, boolean checkWrite) throws IOException { if (!ctx.cFrom().isStarted()) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "task not yet open"); return true; }//from w ww.jav a2s. com if (Solution.SCOPE.equals(scope)) { final SortedMap<String, List<Solution>> filesStud = queries.solutions(ctx); if (!ctx.checkRead(slot, filesStud)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "not readable yet"); return true; } if (checkWrite && !ctx.checkWrite(slot, filesStud)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "not writable yet"); return true; } } return false; }
From source file:org.jboss.as.test.manualmode.web.ssl.HTTPSWebConnectorTestCase.java
/** * @test.tsfi tsfi.keystore.file/*from ww w. j a v a 2s.c om*/ * @test.tsfi tsfi.truststore.file * @test.objective Testing default HTTPs connector with verify-client attribute set to "true". The CLIENT-CERT * authentication (BaseCertLoginModule) is configured for this test. Trusted client is allowed to access * both secured/unsecured resource. Untrusted client is not allowed to access anything. * @test.expectedResult Trusted client has access to protected and unprotected resources. Untrusted client can't access * anything. * @throws Exception */ @Test @InSequence(1) public void testVerifyingConnector() throws Exception { final HttpClient httpClient = getHttpClient(CLIENT_KEYSTORE_FILE); final HttpClient httpClientUntrusted = getHttpClient(UNTRUSTED_KEYSTORE_FILE); try { final URL printPrincipalUrl = getServletUrl(HTTPS_PORT_VERIFY_TRUE, PrincipalPrintingServlet.SERVLET_PATH); final URL securedUrl = getServletUrl(HTTPS_PORT_VERIFY_TRUE, SECURED_SERVLET_WITH_SESSION); final URL unsecuredUrl = getServletUrl(HTTPS_PORT_VERIFY_TRUE, SimpleServlet.SERVLET_PATH); String principal = makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_OK); assertEquals("Unexpected principal", "cn=client", principal.toLowerCase()); String responseBody = makeCallWithHttpClient(securedUrl, httpClient, HttpServletResponse.SC_OK); assertEquals("Secured page was not reached", SimpleSecuredServlet.RESPONSE_BODY, responseBody); try { makeCallWithHttpClient(unsecuredUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN); fail("Untrusted client should not be authenticated."); } catch (SSLHandshakeException | SSLPeerUnverifiedException | SocketException e) { //depending on the OS and the version of HTTP client in use any one of these exceptions may be thrown //in particular the SocketException gets thrown on Windows // OK } try { makeCallWithHttpClient(printPrincipalUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN); fail("Untrusted client should not be authenticated."); } catch (SSLHandshakeException | SSLPeerUnverifiedException | SocketException e) { // OK } try { makeCallWithHttpClient(securedUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN); fail("Untrusted client should not be authenticated."); } catch (SSLHandshakeException | SSLPeerUnverifiedException | SocketException e) { // OK } } finally { httpClient.getConnectionManager().shutdown(); httpClientUntrusted.getConnectionManager().shutdown(); } }
From source file:org.logger.event.web.controller.EventController.java
/** * /*from ww w . j ava2s . c o m*/ * @param request * @param apiKey * @param eventName * @param response * @throws IOException */ @RequestMapping(method = RequestMethod.PUT) public void createEvent(HttpServletRequest request, @RequestParam(value = "apiKey", required = true) String apiKey, @RequestParam(value = EVENT_NAME, required = true) String eventName, HttpServletResponse response) throws IOException { // add cross domain support response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With"); response.setHeader("Access-Control-Allow-Methods", "PUT"); boolean isValid = eventService.ensureValidRequest(request, response); if (!isValid) { eventService.sendErrorResponse(request, response, HttpServletResponse.SC_FORBIDDEN, "Invalid API Key"); return; } response.setContentType("application/json"); if (!eventName.contains(".") || eventName.startsWith(".")) { eventService.sendErrorResponse(request, response, HttpServletResponse.SC_FORBIDDEN, "Invalid Event Name it should be noun.verb "); return; } Map<String, String> status = new HashMap<String, String>(); if (eventService.createEvent(eventName, apiKey)) { status.put(EVENT_NAME, eventName); status.put("status", "Created"); response.getWriter().write(new JSONObject(status).toString()); } else { eventService.sendErrorResponse(request, response, HttpServletResponse.SC_CONFLICT, " Event Already Exists : " + eventName); return; } }
From source file:au.gov.aims.atlasmapperserver.servlet.Proxy.java
private void performTask(HttpServletRequest request, HttpServletResponse response) throws IOException { String clientId = request.getParameter("client"); String urlStr = request.getParameter(URL_PARAM); if (urlStr != null && !urlStr.isEmpty()) { LOGGER.log(Level.INFO, "Proxy URL: {0}", urlStr); try {//from w ww . ja v a2 s . c o m String decodedUrl = URLDecoder.decode(urlStr, "UTF-8"); if (decodedUrl != null) { decodedUrl = decodedUrl.trim(); } URL url = Utils.toURL(decodedUrl); if (url != null) { String protocol = url.getProtocol(); String host = url.getHost(); if (!isHostAllowed(clientId, host)) { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); String responseTxt = "This proxy does not allow you to access that location (" + host + ")."; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } else if (protocol.equals("http") || protocol.equals("https")) { HttpGet httpGet = new HttpGet(url.toURI()); HttpEntity entity = null; try { HttpResponse httpClientResponse = httpClient.execute(httpGet); StatusLine httpStatus = httpClientResponse.getStatusLine(); int responseCode = -1; if (httpStatus != null) { responseCode = httpStatus.getStatusCode(); } response.setStatus(responseCode); if (responseCode < 400) { // The entity is streamed entity = httpClientResponse.getEntity(); String contentType = null; if (entity != null) { Header header = entity.getContentType(); contentType = header.getValue(); } // -1: Unknown status code // 1XX: Informational // 2XX: Successful // 3XX: Redirection if (contentType == null || contentType.isEmpty()) { response.setContentType("text/plain"); LOGGER.log(Level.INFO, "Can not retrieved the content type, falling back to: {0}", response.getContentType()); } else { response.setContentType(contentType); LOGGER.log(Level.INFO, "Set content type using URL connection content type: {0}", response.getContentType()); } InputStream inputStream = null; try { inputStream = entity.getContent(); ServletUtils.sendResponse(response, inputStream); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { LOGGER.log(Level.WARNING, "Cant close the URL input stream: {0}", Utils.getExceptionMessage(e)); LOGGER.log(Level.FINE, "Stack trace: ", e); } } } } else if (responseCode == HttpServletResponse.SC_BAD_REQUEST) { // 400: Bad Request response.setContentType("text/plain"); String responseTxt = "Error " + responseCode + " - Bad Request: " + decodedUrl; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } else if (responseCode == HttpServletResponse.SC_NOT_FOUND) { // 404: Not Found response.setContentType("text/plain"); String responseTxt = "Error " + responseCode + " - Not Found: " + decodedUrl; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } else if (responseCode == HttpServletResponse.SC_INTERNAL_SERVER_ERROR) { // 500: Internal Server Error response.setContentType("text/plain"); String responseTxt = "Error " + responseCode + " - Internal Server Error: " + decodedUrl; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } else { // Any other errors response.setContentType("text/plain"); String responseTxt = "Error " + responseCode + ": " + decodedUrl; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } } finally { if (httpGet != null) { // Cancel the connection, if it's still alive httpGet.abort(); // Close connections httpGet.reset(); } } } else { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); String responseTxt = "Error - Unsupported protocol: " + decodedUrl; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } } } catch (Exception e) { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String responseTxt = "An unexpected error occurred: " + Utils.getExceptionMessage(e); LOGGER.log(Level.WARNING, responseTxt); LOGGER.log(Level.FINE, "Stack trace: ", e); ServletUtils.sendResponse(response, responseTxt); } } else { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); String responseTxt = "Can't get url value from request."; LOGGER.log(Level.WARNING, responseTxt); ServletUtils.sendResponse(response, responseTxt); } }
From source file:com.enonic.cms.web.portal.services.ServicesProcessorBase.java
/** * Process incoming HTTP requests./*from ww w . j a v a 2 s . c om*/ */ private ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response, SitePath sitePath) throws IOException { HttpSession session = request.getSession(true); ExtendedMap formItems = parseForm(request); UserServicesService userServices = lookupUserServices(); SiteKey siteKey = sitePath.getSiteKey(); SitePath originalSitePath = (SitePath) request.getAttribute(Attribute.ORIGINAL_SITEPATH); String handler = UserServicesParameterResolver.resolveHandlerFromSitePath(originalSitePath); String operation = UserServicesParameterResolver.resolveOperationFromSitePath(originalSitePath); if (!userServicesAccessManager.isOperationAllowed(siteKey, handler, operation)) { String message = "Access to http service '" + handler + "." + operation + "' on site " + siteKey + " is not allowed by configuration. Check the settings in site-" + siteKey + ".properties"; VerticalUserServicesLogger.warn(message); String httpErrorMsg = "Access denied to http service '" + handler + "." + operation + "' on site " + siteKey; response.sendError(HttpServletResponse.SC_FORBIDDEN, httpErrorMsg); return null; } // check if domain in redirect URL is allowed final String redirect = formItems.getString("_redirect", null); final String redirectUrl = userServicesRedirectUrlResolver.resolveRedirectUrlToPage(request, redirect, null); if (!isRedirectUrlAllowed(redirectUrl)) { final String domain = new URL(redirectUrl).getHost(); final String message = String.format( "Domain '%s' of redirect URL not allowed (%s), in request to HTTP service '%s.%s' on site %s. " + "Check setting 'cms.httpServices.redirect.allowedDomains' in cms.properties", domain, redirectUrl, handler, operation, siteKey); VerticalUserServicesLogger.warn(message); final String httpErrorMsg = String.format("Domain of redirect URL not allowed: %s", domain); response.sendError(HttpServletResponse.SC_FORBIDDEN, httpErrorMsg); return null; } try { if (!(this instanceof FormServicesProcessor)) { // Note: The FormHandlerController is doing its own validation. Boolean captchaOk = captchaService.validateCaptcha(formItems, request, handler, operation); if ((captchaOk != null) && (!captchaOk)) { VerticalSession vsession = (VerticalSession) session .getAttribute(VerticalSession.VERTICAL_SESSION_OBJECT); if (vsession == null) { vsession = new VerticalSession(); session.setAttribute(VerticalSession.VERTICAL_SESSION_OBJECT, vsession); } vsession.setAttribute("error_" + handler + "_" + operation, captchaService.buildErrorXMLForSessionContext(formItems).getAsDOMDocument()); redirectToErrorPage(request, response, formItems, ERR_INVALID_CAPTCHA); return null; } } if ("create".equals(operation)) { handlerCreate(request, response, session, formItems, userServices, siteKey); } else if ("update".equals(operation)) { handlerUpdate(request, response, session, formItems, userServices, siteKey); } else if ("remove".equals(operation)) { handlerRemove(request, response, session, formItems, userServices, siteKey); } else { handlerCustom(request, response, session, formItems, userServices, siteKey, operation); } } catch (VerticalSecurityException vse) { String message = "No rights to handle request: %t"; VerticalUserServicesLogger.warn(message, vse); redirectToErrorPage(request, response, formItems, ERR_SECURITY_EXCEPTION); } catch (ContentAccessException vse) { String message = "No rights to handle request: %t"; VerticalUserServicesLogger.warn(message, vse); redirectToErrorPage(request, response, formItems, ERR_SECURITY_EXCEPTION); } catch (CategoryAccessException vse) { String message = "No rights to handle request: %t"; VerticalUserServicesLogger.warn(message, vse); redirectToErrorPage(request, response, formItems, ERR_SECURITY_EXCEPTION); } catch (UserServicesException use) { throw use; } catch (Exception e) { String message = "Failed to handle request: %t"; VerticalUserServicesLogger.error(message, e); redirectToErrorPage(request, response, formItems, ERR_OPERATION_BACKEND); } return null; }