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:org.logger.event.web.controller.EventController.java
/** * Get last few events//from w ww.jav a 2 s. c o m * * @param request * @param apiKey * @param totalRows * @param response */ @RequestMapping(value = "/latest/tail", method = RequestMethod.GET) public void readLastNevents(HttpServletRequest request, @RequestParam(value = "apiKey", required = true) String apiKey, @RequestParam(value = "totalRows", defaultValue = "20", required = false) Integer totalRows, HttpServletResponse response) { // 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", "GET, PUT, POST"); String apiKeyToken = request.getParameter("apiKey"); if (apiKeyToken != null && apiKeyToken.length() == 36) { AppDO appDO = eventService.verifyApiKey(apiKeyToken); if (appDO != null) { Rows<String, String> eventDetailRows = eventService.readLastNevents(apiKey, totalRows); if (eventDetailRows != null && !eventDetailRows.isEmpty()) { List<Map<String, Object>> eventJSONList = new ArrayList<Map<String, Object>>(); response.setContentType("application/json"); // Iterate through cassandra rows and get the event JSONS for (Row<String, String> row : eventDetailRows) { Map<String, Object> resultMap = new HashMap<String, Object>(); resultMap.put("eventJSON", row.getColumns().getStringValue("fields", null)); resultMap.put("startTime", row.getColumns().getLongValue("start_time", null)); resultMap.put("endTime", row.getColumns().getLongValue("end_time", null)); resultMap.put(EVENT_NAME, row.getColumns().getStringValue("event_name", null)); resultMap.put("apiKey", row.getColumns().getStringValue("api_key", null)); eventJSONList.add(resultMap); } JSONObject resultJson = new JSONObject(eventJSONList); try { response.getWriter().write(resultJson.toString()); } catch (IOException e) { logger.error("OOPS! Something went wrong", e); } } return; } } eventService.sendErrorResponse(request, response, HttpServletResponse.SC_FORBIDDEN, "Invalid API Key"); return; }
From source file:org.dasein.cloud.vcloud.vCloudMethod.java
private void loadOrg(@Nonnull String endpoint, @Nonnull Org org, @Nonnull String orgId) throws CloudException, InternalException { String xml;// ww w .j a v a2 s. c o m if (wire.isDebugEnabled()) { wire.debug(""); wire.debug(">>> [GET (" + (new Date()) + ")] -> " + endpoint + " >--------------------------------------------------------------------------------------"); } try { HttpClient client = getClient(false); HttpGet get = new HttpGet(endpoint); get.addHeader("Accept", "application/*+xml;version=" + org.version.version + ",application/*+xml;version=" + org.version.version); addAuth(get, org.token); if (wire.isDebugEnabled()) { wire.debug(get.getRequestLine().toString()); for (Header header : get.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } HttpResponse response; try { APITrace.trace(provider, "GET org"); response = client.execute(get); if (wire.isDebugEnabled()) { wire.debug(response.getStatusLine().toString()); for (Header header : response.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); } } catch (IOException e) { logger.error("I/O error from server communications: " + e.getMessage()); throw new InternalException(e); } int code = response.getStatusLine().getStatusCode(); logger.debug("HTTP STATUS: " + code); if (code == HttpServletResponse.SC_NOT_FOUND || code == HttpServletResponse.SC_FORBIDDEN) { throw new CloudException("Org URL is invalid"); } else if (code == HttpServletResponse.SC_UNAUTHORIZED) { authenticate(true); loadOrg(endpoint, org, orgId); return; } else if (code == HttpServletResponse.SC_NO_CONTENT) { throw new CloudException("No content from org URL"); } else if (code == HttpServletResponse.SC_OK) { try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } else { xml = null; } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } } else { logger.error("Expected OK for GET request, got " + code); try { HttpEntity entity = response.getEntity(); if (entity != null) { xml = EntityUtils.toString(entity); if (wire.isDebugEnabled()) { wire.debug(xml); wire.debug(""); } } else { xml = null; } } catch (IOException e) { logger.error("Failed to read response error due to a cloud I/O error: " + e.getMessage()); throw new CloudException(e); } vCloudException.Data data = null; if (xml != null && !xml.equals("")) { Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList errors = doc.getElementsByTagName(nsString + "Error"); if (errors.getLength() > 0) { data = vCloudException.parseException(code, errors.item(0)); } } if (data == null) { throw new vCloudException(CloudErrorType.GENERAL, code, response.getStatusLine().getReasonPhrase(), "No further information"); } logger.error("[" + code + " : " + data.title + "] " + data.description); throw new vCloudException(data); } } finally { if (wire.isDebugEnabled()) { wire.debug("<<< [GET (" + (new Date()) + ")] -> " + endpoint + " <--------------------------------------------------------------------------------------"); wire.debug(""); } } if (xml == null) { throw new CloudException("No content from org URL"); } Document doc = parseXML(xml); String docElementTagName = doc.getDocumentElement().getTagName(); String nsString = ""; if (docElementTagName.contains(":")) nsString = docElementTagName.substring(0, docElementTagName.indexOf(":") + 1); NodeList orgList = doc.getElementsByTagName(nsString + "Org"); for (int i = 0; i < orgList.getLength(); i++) { Node orgNode = orgList.item(i); if (orgNode.hasAttributes()) { Node type = orgNode.getAttributes().getNamedItem("type"); if (type != null && type.getNodeValue().trim().equals(getMediaTypeForOrg())) { Node name = orgNode.getAttributes().getNamedItem("name"); if (name != null && name.getNodeValue().trim().equals(orgId)) { Node href = orgNode.getAttributes().getNamedItem("href"); if (href != null) { Region region = new Region(); String url = href.getNodeValue().trim(); region.setActive(true); region.setAvailable(true); if (provider.isCompat()) { region.setProviderRegionId("/org/" + url.substring(url.lastIndexOf('/') + 1)); } else { region.setProviderRegionId(url.substring(url.lastIndexOf('/') + 1)); } region.setJurisdiction("US"); region.setName(name.getNodeValue().trim()); org.endpoint = url.substring(0, url.lastIndexOf("/api/org")); org.region = region; org.url = url; return; } } } } } throw new CloudException("Could not find " + orgId + " among listed orgs"); }
From source file:alpha.portal.webapp.controller.UserFormController.java
/** * Show form.//from w w w.j av a 2 s . c om * * @param request * the request * @param response * the response * @return the model and view * @throws Exception * the exception */ @ModelAttribute @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) protected ModelAndView showForm(final HttpServletRequest request, final HttpServletResponse response) throws Exception { final ModelAndView model = new ModelAndView(); User user; // If not an administrator, make sure user is not trying to add or edit // another user if (!request.isUserInRole(Constants.ADMIN_ROLE) && !this.isFormSubmission(request)) { if (this.isAdd(request) || (request.getParameter("id") != null)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); this.log.warn("User '" + request.getRemoteUser() + "' is trying to edit user with id '" + request.getParameter("id") + "'"); throw new AccessDeniedException("You do not have permission to modify other users."); } } if (!this.isFormSubmission(request)) { final String userId = request.getParameter("id"); // if user logged in with remember me, display a warning that they // can't change passwords this.log.debug("checking for remember me login..."); final AuthenticationTrustResolver resolver = new AuthenticationTrustResolverImpl(); final SecurityContext ctx = SecurityContextHolder.getContext(); if (ctx.getAuthentication() != null) { final Authentication auth = ctx.getAuthentication(); if (resolver.isRememberMe(auth)) { request.getSession().setAttribute("cookieLogin", "true"); // add warning message this.saveMessage(request, this.getText("userProfile.cookieLogin", request.getLocale())); } } if ((userId == null) && !this.isAdd(request)) { user = this.getUserManager().getUserByUsername(request.getRemoteUser()); } else if (!StringUtils.isBlank(userId) && !"".equals(request.getParameter("version"))) { user = this.getUserManager().getUser(userId); } else { user = new User(); user.addRole(new Role(Constants.USER_ROLE)); } user.setConfirmPassword(user.getPassword()); UserExtension userExtension; final Long uId = user.getId(); if ((uId != null) && this.userExtensionManager.exists(uId)) { userExtension = this.userExtensionManager.get(uId); } else { userExtension = new UserExtension(user); } model.addObject("userExtension", userExtension); model.addObject("contributorRoles", this.contributorRoleManager.getAll()); } else { // populate user object from database, so all fields don't need to // be hidden fields in form user = this.getUserManager().getUser(request.getParameter("id")); } model.addObject("user", user); return model; }
From source file:org.jetbrains.webdemo.sessions.MyHttpSession.java
private void sendAddAdventOfCodeProjectResult() { try {/* w ww. j a v a 2 s. c o m*/ String inputFileContent = request.getParameter("inputFileContent"); String name = request.getParameter("name"); String publicIds = MySqlConnector.getInstance().addAdventOfCodeProject(sessionInfo.getUserInfo(), name, inputFileContent); writeResponse(publicIds, HttpServletResponse.SC_OK); } catch (NullPointerException e) { writeResponse("Can't get parameters", HttpServletResponse.SC_BAD_REQUEST); } catch (DatabaseOperationException e) { writeResponse(e.getMessage(), HttpServletResponse.SC_FORBIDDEN); } }
From source file:com.enonic.vertical.userservices.AbstractUserServicesHandlerController.java
/** * Process incoming HTTP requests./*w w w . j a v a 2 s . co m*/ */ public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response, SitePath sitePath) throws ServletException, 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(this.getClass(), 0, message, null); String httpErrorMsg = "Access denied to http service '" + handler + "." + operation + "' on site " + siteKey; response.sendError(HttpServletResponse.SC_FORBIDDEN, httpErrorMsg); return null; } try { if (!(this instanceof FormHandlerController)) { // 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, null); 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 (CaptchaServiceException e) { String message = "Failed during captcha validation: %t"; VerticalUserServicesLogger.error(this.getClass(), 0, message, e); redirectToErrorPage(request, response, formItems, ERR_OPERATION_BACKEND, null); } catch (VerticalUserServicesException vuse) { String message = "Failed to handle request: %t"; VerticalUserServicesLogger.error(this.getClass(), 0, message, vuse); redirectToErrorPage(request, response, formItems, ERR_OPERATION_HANDLER, null); } catch (VerticalUpdateException vue) { String message = "Failed to handle update request: %t"; VerticalUserServicesLogger.warn(this.getClass(), 0, message, vue); redirectToErrorPage(request, response, formItems, ERR_OPERATION_BACKEND, null); } catch (VerticalRemoveException vre) { String message = "Failed to handle remove request: %t"; VerticalUserServicesLogger.warn(this.getClass(), 0, message, vre); redirectToErrorPage(request, response, formItems, ERR_OPERATION_BACKEND, null); } catch (VerticalSecurityException vse) { String message = "No rights to handle request: %t"; VerticalUserServicesLogger.warn(this.getClass(), 0, message, vse); redirectToErrorPage(request, response, formItems, ERR_SECURITY_EXCEPTION, null); } catch (ContentAccessException vse) { String message = "No rights to handle request: %t"; VerticalUserServicesLogger.warn(this.getClass(), 0, message, vse); redirectToErrorPage(request, response, formItems, ERR_SECURITY_EXCEPTION, null); } catch (CategoryAccessException vse) { String message = "No rights to handle request: %t"; VerticalUserServicesLogger.warn(this.getClass(), 0, message, vse); redirectToErrorPage(request, response, formItems, ERR_SECURITY_EXCEPTION, null); } catch (VerticalEngineException vee) { String message = "Failed to handle engine request: %t"; VerticalUserServicesLogger.warn(this.getClass(), 0, message, vee); redirectToErrorPage(request, response, formItems, ERR_OPERATION_BACKEND, null); } catch (UserServicesException use) { throw use; } catch (Exception e) { String message = "Failed to handle request: %t"; VerticalUserServicesLogger.error(this.getClass(), 0, message, e); redirectToErrorPage(request, response, formItems, ERR_OPERATION_BACKEND, null); } return null; }
From source file:com.jpeterson.littles3.StorageEngine.java
/** * Process HTTP HEAD and GET/*from w w w .ja v a 2 s. c om*/ * * @param req * an HttpServletRequest object that contains the request the * client has made of the servlet * @param resp * an HttpServletResponse object that contains the response the * servlet sends to the client * @throws IOException * if an input or output error is detected when the servlet * handles the GET request * @throws ServletException * if the request for the GET could not be handled */ @SuppressWarnings("unchecked") public void processHeadGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (logger.isDebugEnabled()) { logger.debug("Context path: " + req.getContextPath()); logger.debug("Path info: " + req.getPathInfo()); logger.debug("Path translated: " + req.getPathTranslated()); logger.debug("Query string: " + req.getQueryString()); logger.debug("Request URI: " + req.getRequestURI()); logger.debug("Request URL: " + req.getRequestURL()); logger.debug("Servlet path: " + req.getServletPath()); logger.debug("Servlet name: " + this.getServletName()); for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) { String headerName = (String) headerNames.nextElement(); String headerValue = req.getHeader(headerName); logger.debug("Header- " + headerName + ": " + headerValue); } } try { S3ObjectRequest or; try { or = S3ObjectRequest.create(req, resolvedHost(), (Authenticator) getWebApplicationContext().getBean(BEAN_AUTHENTICATOR)); } catch (InvalidAccessKeyIdException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidAccessKeyId"); return; } catch (InvalidSecurityException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity"); return; } catch (RequestTimeTooSkewedException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "RequestTimeTooSkewed"); return; } catch (SignatureDoesNotMatchException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "SignatureDoesNotMatch"); return; } catch (AuthenticatorException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_FORBIDDEN, "InvalidSecurity"); return; } if (or.getKey() != null) { S3Object s3Object; StorageService storageService; try { storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); s3Object = storageService.load(or.getBucket(), or.getKey()); if (s3Object == null) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey"); return; } } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchKey"); return; } if (req.getParameter(PARAMETER_ACL) != null) { // retrieve access control policy String response; Acp acp = s3Object.getAcp(); try { acp.canRead(or.getRequestor()); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } response = Acp.encode(acp); resp.setContentLength(response.length()); resp.setContentType("application/xml"); resp.setStatus(HttpServletResponse.SC_OK); Writer out = resp.getWriter(); out.write(response); out.flush(); // commit response out.close(); out = null; } else { // retrieve object InputStream in = null; OutputStream out = null; byte[] buffer = new byte[4096]; int count; String value; try { s3Object.canRead(or.getRequestor()); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } // headers resp.setContentType(s3Object.getContentType()); if ((value = s3Object.getContentDisposition()) != null) { resp.setHeader("Content-Disposition", value); } // TODO: set the Content-Range, if request includes Range // TODO: add "x-amz-missing-meta", if any // add the "x-amz-meta-" headers for (Iterator<String> names = s3Object.getMetadataNames(); names.hasNext();) { String name = names.next(); String headerName = HEADER_PREFIX_USER_META + name; String prefix = ""; StringBuffer buf = new StringBuffer(); for (Iterator<String> values = s3Object.getMetadataValues(name); values.hasNext();) { buf.append(values.next()).append(prefix); prefix = ","; } resp.setHeader(headerName, buf.toString()); } resp.setDateHeader("Last-Modified", s3Object.getLastModified()); if ((value = s3Object.getETag()) != null) { resp.setHeader("ETag", value); } if ((value = s3Object.getContentMD5()) != null) { resp.setHeader("Content-MD5", value); } if ((value = s3Object.getContentDisposition()) != null) { resp.setHeader("Content-Disposition", value); } resp.setHeader("Accept-Ranges", "bytes"); String rangeRequest = req.getHeader("Range"); if (rangeRequest != null) { // request for a range RangeSet rangeSet = RangeFactory.processRangeHeader(rangeRequest); // set content length rangeSet.resolve(s3Object.getContentLength()); if (rangeSet.size() > 1) { // requires multi-part response // TODO: implement resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); } Range[] ranges = (Range[]) rangeSet.toArray(new Range[0]); resp.setHeader("Content-Range", formatRangeHeaderValue(ranges[0], s3Object.getContentLength())); resp.setHeader("Content-Length", Long.toString(rangeSet.getLength())); in = new RangeInputStream(s3Object.getInputStream(), ranges[0]); resp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); } else { // request for entire content // Used instead of resp.setContentLength((int)); because // Amazon // limit is 5 gig, which is bigger than an int resp.setHeader("Content-Length", Long.toString(s3Object.getContentLength())); in = s3Object.getInputStream(); resp.setStatus(HttpServletResponse.SC_OK); } // body out = resp.getOutputStream(); while ((count = in.read(buffer, 0, buffer.length)) > 0) { out.write(buffer, 0, count); } out.flush(); // commit response out.close(); out = null; } return; } else if (or.getBucket() != null) { // operation on a bucket StorageService storageService; String prefix; String marker; int maxKeys = Integer.MAX_VALUE; String delimiter; String response; String value; storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); if (req.getParameter(PARAMETER_ACL) != null) { // retrieve access control policy Acp acp; try { acp = storageService.loadBucket(or.getBucket()).getAcp(); } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } try { acp.canRead(or.getRequestor()); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } response = Acp.encode(acp); resp.setContentLength(response.length()); resp.setContentType("application/xml"); resp.setStatus(HttpServletResponse.SC_OK); Writer out = resp.getWriter(); out.write(response); out.flush(); // commit response out.close(); out = null; } else { Bucket bucket; prefix = req.getParameter("prefix"); if (prefix == null) { prefix = ""; } marker = req.getParameter("marker"); value = req.getParameter("max-keys"); if (value != null) { try { maxKeys = Integer.parseInt(value); } catch (NumberFormatException e) { logger.info("max-keys must be numeric: " + value); } } delimiter = req.getParameter("delimiter"); try { bucket = storageService.loadBucket(or.getBucket()); } catch (DataAccessException e) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, "NoSuchBucket"); return; } try { bucket.canRead(or.getRequestor()); } catch (AccessControlException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "AccessDenied"); return; } response = storageService.listKeys(bucket, prefix, marker, delimiter, maxKeys); resp.setContentLength(response.length()); resp.setContentType("application/xml"); resp.setStatus(HttpServletResponse.SC_OK); Writer out = resp.getWriter(); out.write(response); if (logger.isTraceEnabled()) { logger.trace("Response: " + response); } } return; } else { // operation on the service StorageService storageService; List buckets; storageService = (StorageService) getWebApplicationContext().getBean(BEAN_STORAGE_SERVICE); buckets = storageService.findBuckets(""); StringBuffer buffer = new StringBuffer(); buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); buffer.append("<ListAllMyBucketsResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"); buffer.append("<Owner>"); buffer.append("<ID/>"); // TODO: implement buffer.append("<DisplayName/>"); // TODO: implementF buffer.append("</Owner>"); buffer.append("<Buckets>"); for (Iterator iter = buckets.iterator(); iter.hasNext();) { Bucket bucket = (Bucket) iter.next(); buffer.append("<Bucket>"); buffer.append("<Name>").append(bucket.getName()).append("</Name>"); buffer.append("<CreationDate>").append(iso8601.format(bucket.getCreated())) .append("</CreationDate>"); buffer.append("</Bucket>"); } buffer.append("</Buckets>"); buffer.append("</ListAllMyBucketsResult>"); resp.setContentLength(buffer.length()); resp.setContentType("application/xml"); resp.setStatus(HttpServletResponse.SC_OK); Writer out = resp.getWriter(); out.write(buffer.toString()); return; } } catch (IllegalArgumentException e) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidURI"); return; } }
From source file:jp.or.openid.eiwg.scim.servlet.Users.java
/** * PATCH?//from w w w . j a v a2s .c om * * @param request * @param response ? * @throws ServletException * @throws IOException */ protected void doPatch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ? errorResponse(response, HttpServletResponse.SC_FORBIDDEN, null, MessageConstants.ERROR_NOT_SUPPORT_OPERATION); }
From source file:org.jboss.as.test.manualmode.web.ssl.HTTPSWebConnectorTestCase.java
/** * @test.tsfi tsfi.keystore.file/*from w w w .j a v a2 s .c o m*/ * @test.tsfi tsfi.truststore.file * @test.objective Testing default HTTPs connector with verify-client attribute set to "want". The CLIENT-CERT * authentication (BaseCertLoginModule) is configured for this test. Trusted client is allowed to access * both secured/unsecured resource. Untrusted client can only access unprotected resources. * @test.expectedResult Trusted client has access to protected and unprotected resources. Untrusted client has only access * to unprotected resources. * @throws Exception */ @Test @InSequence(1) public void testWantVerifyConnector() throws Exception { Assume.assumeFalse( SystemUtils.IS_JAVA_1_6 && SystemUtils.JAVA_VENDOR.toUpperCase(Locale.ENGLISH).contains("IBM")); final URL printPrincipalUrl = getServletUrl(HTTPS_PORT_VERIFY_WANT, PrincipalPrintingServlet.SERVLET_PATH); final URL securedUrl = getServletUrl(HTTPS_PORT_VERIFY_WANT, SECURED_SERVLET_WITH_SESSION); final URL unsecuredUrl = getServletUrl(HTTPS_PORT_VERIFY_WANT, SimpleServlet.SERVLET_PATH); final HttpClient httpClient = getHttpClient(CLIENT_KEYSTORE_FILE); final HttpClient httpClientUntrusted = getHttpClient(UNTRUSTED_KEYSTORE_FILE); try { makeCallWithHttpClient(printPrincipalUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN); final String principal = makeCallWithHttpClient(printPrincipalUrl, httpClient, HttpServletResponse.SC_OK); assertEquals("Unexpected principal", "cn=client", principal.toLowerCase()); String responseBody = makeCallWithHttpClient(unsecuredUrl, httpClient, HttpServletResponse.SC_OK); assertEquals("Unsecured page was not reached", SimpleSecuredServlet.RESPONSE_BODY, responseBody); responseBody = makeCallWithHttpClient(securedUrl, httpClient, HttpServletResponse.SC_OK); assertEquals("Secured page was not reached", SimpleSecuredServlet.RESPONSE_BODY, responseBody); responseBody = makeCallWithHttpClient(unsecuredUrl, httpClientUntrusted, HttpServletResponse.SC_OK); assertEquals("Unsecured page was not reached", SimpleServlet.RESPONSE_BODY, responseBody); makeCallWithHttpClient(securedUrl, httpClientUntrusted, HttpServletResponse.SC_FORBIDDEN); } finally { httpClient.getConnectionManager().shutdown(); httpClientUntrusted.getConnectionManager().shutdown(); } }
From source file:com.alfaariss.oa.authentication.remote.saml2.profile.re.ResponseEndpoint.java
/** * @see com.alfaariss.oa.util.saml2.profile.ISAML2Profile#process(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from ww w. j a va 2 s. c o m*/ public void process(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws OAException { String sURL = servletRequest.getRequestURL().toString(); if (sURL.endsWith("/")) sURL = sURL.substring(0, sURL.length() - 1); _logger.debug("Servicing response: " + sURL); try { if (sURL.endsWith(REDIRECTER)) { processRedirect(servletRequest, servletResponse); } else { AbstractDecodingFactory decFactory = AbstractDecodingFactory.resolveInstance(servletRequest, servletResponse, _bindingProperties); if (decFactory == null) { _logger.error("No decode factory available for request"); throw new OAException(SystemErrors.ERROR_INTERNAL); } SAMLMessageDecoder decoder = decFactory.getDecoder(); //check all supported bindings String sBindingURI = decoder.getBindingURI(); if (!_bindingProperties.isSupported(sBindingURI)) { _logger.error("The binding is not supported by this protocol: " + sBindingURI); throw new OAException(SystemErrors.ERROR_INTERNAL); } //decode request SAMLMessageContext<SignableSAMLObject, SignableSAMLObject, SAMLObject> context = decFactory .getContext(); //use metadata from requestors to set chainedMetadataProvider for current //issuer String val = servletRequest.getParameter("SAMLart"); if (val != null) { //SAML artifact received, requestor metadata and IssuerID must be added //in order to enable the decoder to decode artifact byte[] bb = Base64.decode(val); SAML2ArtifactType0004 b = null; SAML2ArtifactType0004Builder bf = new SAML2ArtifactType0004Builder(); b = bf.buildArtifact(bb); IIDP org = _idpStorageManager.getIDP(b.getSourceID(), SAML2IDP.TYPE_SOURCEID); if (org != null && org instanceof SAML2IDP) { SAML2IDP saml2IDP = (SAML2IDP) org; context.setMetadataProvider(saml2IDP.getMetadataProvider()); context.setInboundMessageIssuer(saml2IDP.getID()); context.setOutboundMessageIssuer(_sEntityID); } else { StringBuffer sbDebug = new StringBuffer( "Unknown organization specified with with SourceID '"); sbDebug.append(Arrays.toString(b.getSourceID())); sbDebug.append("' in artifact: "); sbDebug.append(val); _logger.debug(sbDebug.toString()); throw new MessageDecodingException("Could not find metadata for decoding artifact"); } } //decode context decoder.decode(context); processResponse(servletRequest, servletResponse, context); } } catch (MessageDecodingException e) { _logger.debug("Could not decode XML in SAML request message", e); try { if (!servletResponse.isCommitted()) servletResponse.sendError(HttpServletResponse.SC_BAD_REQUEST); } catch (IOException e1) { _logger.warn("Could not send response", e1); } } catch (SecurityException e) { _logger.debug("the decoded message does not meet the required security constraints", e); try { if (!servletResponse.isCommitted()) servletResponse.sendError(HttpServletResponse.SC_FORBIDDEN); } catch (IOException e1) { _logger.warn("Could not send response", e1); } } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Could not process SAML request message", e); throw new OAException(SystemErrors.ERROR_INTERNAL); } }