List of usage examples for javax.servlet.http Cookie setPath
public void setPath(String uri)
From source file:org.infoglue.cms.security.InfoGlueAuthenticationFilter.java
/** * This filter is basically what secures Infoglue and enforces the authentication framework. *///from ww w .ja va 2 s . c o m public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws ServletException, IOException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; try { if (CmsPropertyHandler.getServletContext() == null) { CmsPropertyHandler.setServletContext(httpServletRequest.getContextPath()); } String URI = httpServletRequest.getRequestURI(); String URL = httpServletRequest.getRequestURL().toString(); if (logger.isInfoEnabled()) { logger.info("URI: + " + URI); logger.info("URL: + " + URL); } String requestURI = URLDecoder.decode(getContextRelativeURI(httpServletRequest), "UTF-8"); if (URI == null) logger.error("URI was null - requestURI:" + requestURI); if (URL == null) logger.error("URL was null - requestURI:" + requestURI); if (requestURI == null) logger.error("requestURI was null"); if (loginUrl == null) { logger.error("loginUrl was null - fix this."); loginUrl = "Login.action"; } if (invalidLoginUrl == null) { logger.error("invalidLoginUrl was null - fix this."); invalidLoginUrl = "Login!invalidLogin.action"; } if (logoutUrl == null) { logger.error("logoutUrl was null - fix this."); logoutUrl = "ExtranetLogin!logout.action"; } if (uriMatcher == null) { logger.error("uriMatcher was null - fix this."); String filterURIs = filterConfig.getInitParameter(FILTER_URIS_PARAMETER); uriMatcher = URIMatcher.compilePatterns(splitString(filterURIs, ","), false); } if (!CmsPropertyHandler.getIsValidSetup() && (URI.indexOf("Install") == -1 && URI.indexOf(".action") > -1)) { httpServletResponse.sendRedirect("Install!input.action"); return; } //Here are the url:s/paths that must be skipped by the security framework for it to work. Login screens etc must be reachable naturally. if (URI != null && URL != null && (URI.indexOf(loginUrl) > -1 || URL.indexOf(loginUrl) > -1 || URI.indexOf("Login.action") > -1 || URL.indexOf("Login.action") > -1 || URI.indexOf(invalidLoginUrl) > -1 || URL.indexOf(invalidLoginUrl) > -1 || URI.indexOf("Login!invalidLogin.action") > -1 || URL.indexOf("Login!invalidLogin.action") > -1 || URI.indexOf(logoutUrl) > -1 || URI.indexOf("Login!logout.action") > -1 || URL.indexOf(logoutUrl) > -1 || URI.indexOf("UpdateCache") > -1 || URI.indexOf("protectedRedirect.jsp") > -1 || uriMatcher.matches(requestURI))) { fc.doFilter(request, response); return; } // make sure we've got an HTTP request if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) throw new ServletException("InfoGlue Filter protects only HTTP resources"); HttpSession session = ((HttpServletRequest) request).getSession(); String sessionTimeout = CmsPropertyHandler.getSessionTimeout(); try { Integer.parseInt(sessionTimeout); } catch (Exception e) { sessionTimeout = "1800"; } if (sessionTimeout == null) sessionTimeout = "1800"; session.setMaxInactiveInterval(new Integer(sessionTimeout).intValue()); // if our attribute's already present, don't do anything //logger.info("User:" + session.getAttribute(INFOGLUE_FILTER_USER)); if (session != null && session.getAttribute(INFOGLUE_FILTER_USER) != null) { //logger.info("Found user in session:" + session.getAttribute(INFOGLUE_FILTER_USER)); //if(successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl)) //{ // checkSuccessRedirect(request, response, URL); //} //else //{ fc.doFilter(request, response); return; //} } // otherwise, we need to authenticate somehow boolean isAdministrator = false; String userName = request.getParameter("j_username"); String password = request.getParameter("j_password"); if (userName != null && password != null) { String administratorUserName = CmsPropertyHandler.getAdministratorUserName(); boolean matchesRootPassword = CmsPropertyHandler.getMatchesAdministratorPassword(password); isAdministrator = (userName.equalsIgnoreCase(administratorUserName) && matchesRootPassword) ? true : false; } //First we check if the user is logged in to the container context if (!isAdministrator) { logger.info("Principal:" + httpServletRequest.getUserPrincipal()); if (httpServletRequest.getUserPrincipal() != null && !(httpServletRequest.getUserPrincipal() instanceof InfoGluePrincipal)) { userName = httpServletRequest.getUserPrincipal().getName(); logger.info("Now trusting the container logged in identity..."); } } String authenticatedUserName = userName; if (!isAdministrator) { String encodedUserNameCookie = httpHelper.getCookie(httpServletRequest, "iguserid"); logger.info("encodedUserNameCookie:" + encodedUserNameCookie); if (encodedUserNameCookie != null && !encodedUserNameCookie.equals("")) { byte[] bytes = Base64.decodeBase64(encodedUserNameCookie); encodedUserNameCookie = new String(bytes, "utf-8"); //encodedUserNameCookie = encodedUserNameCookie.replaceAll("IGEQ", "="); logger.info("encodedUserNameCookie:" + encodedUserNameCookie); String servletContextUserName = (String) filterConfig.getServletContext() .getAttribute(encodedUserNameCookie); logger.info("servletContextUserName:" + servletContextUserName); if (servletContextUserName != null && !servletContextUserName.equals("")) { authenticatedUserName = servletContextUserName; } else { Cookie cookie_iguserid = new Cookie("iguserid", "none"); cookie_iguserid.setPath("/"); cookie_iguserid.setMaxAge(0); httpServletResponse.addCookie(cookie_iguserid); Cookie cookie_igpassword = new Cookie("igpassword", "none"); cookie_igpassword.setPath("/"); cookie_igpassword.setMaxAge(0); httpServletResponse.addCookie(cookie_igpassword); authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc); } } else { authenticatedUserName = authenticateUser(httpServletRequest, httpServletResponse, fc); } } logger.info("authenticatedUserName:" + authenticatedUserName); if (authenticatedUserName != null) { logger.info("Getting the principal from user name:" + authenticatedUserName); InfoGluePrincipal user = getAuthenticatedUser(authenticatedUserName); if (user == null || (!user.getIsAdministrator() && !hasAuthorizedRole(user))) { //throw new Exception("This user is not authorized to log in..."); httpServletResponse.sendRedirect("unauthorizedLogin.jsp"); NotificationMessage notificationMessage = new NotificationMessage("Authorization failed:", "Authorization", authenticatedUserName, NotificationMessage.AUTHORIZATION_FAILED, "" + authenticatedUserName, "name"); TransactionHistoryController.getController().create(notificationMessage); return; } //TODO - we must fix so these caches are individual to the person - now a login will slow down for all //CacheController.clearCache("authorizationCache"); //CacheController.clearCache("personalAuthorizationCache", user.getName()); CacheController.clearCacheForGroup("personalAuthorizationCache", user.getName()); // Store the authenticated user in the session if (session != null) { session.setAttribute(INFOGLUE_FILTER_USER, user); setUserProperties(session, user); } //TEST - transferring auth to deliverworking try { if (userName != null && password != null) { DesEncryptionHelper encHelper = new DesEncryptionHelper(); String encryptedName = encHelper.encrypt(userName); String encryptedPassword = encHelper.encrypt(password); String encryptedNameAsBase64 = Base64 .encodeBase64URLSafeString(encryptedName.getBytes("utf-8")); String encryptedPasswordAsBase64 = Base64 .encodeBase64URLSafeString(encryptedPassword.getBytes("utf-8")); String deliverBaseUrl = CmsPropertyHandler.getComponentRendererUrl(); String[] parts = deliverBaseUrl.split("/"); deliverBaseUrl = "/" + parts[parts.length - 1]; //logger.info("used cmsBaseUrl:" + cmsBaseUrl); ServletContext servletContext = filterConfig.getServletContext().getContext(deliverBaseUrl); if (servletContext == null) { logger.error("Could not autologin to " + deliverBaseUrl + ". Set cross context = true in Tomcat config."); } else { logger.info("Added encryptedName:" + encryptedName + " = " + user.getName() + " to deliver context"); servletContext.setAttribute(encryptedName, user.getName()); } int cmsCookieTimeout = 1800; //30 minutes default String cmsCookieTimeoutString = null; //CmsPropertyHandler.getCmsCookieTimeout(); if (cmsCookieTimeoutString != null) { try { cmsCookieTimeout = Integer.parseInt(cmsCookieTimeoutString.trim()); } catch (Exception e) { } } //Cookie cookie_iguserid = new Cookie("iguserid", encryptedName.replaceAll("=", "IGEQ")); Cookie cookie_iguserid = new Cookie("iguserid", encryptedNameAsBase64); cookie_iguserid.setPath("/"); cookie_iguserid.setMaxAge(cmsCookieTimeout); httpServletResponse.addCookie(cookie_iguserid); //Cookie cookie_igpassword = new Cookie ("igpassword", encryptedPassword.replaceAll("=", "IGEQ")); Cookie cookie_igpassword = new Cookie("igpassword", encryptedPasswordAsBase64); cookie_igpassword.setPath("/"); cookie_igpassword.setMaxAge(cmsCookieTimeout); httpServletResponse.addCookie(cookie_igpassword); //logger.info(encryptedName + "=" + userName); //logger.info("After attribute:" + servletContext.getAttribute(encryptedName)); } } catch (Exception e) { logger.error("Error: " + e.getMessage(), e); } //END TEST String logUserName = userName; if (logUserName == null || logUserName.equals("") && user != null) logUserName = user.getName(); if (logUserName == null || logUserName.equals("")) logUserName = authenticatedUserName; if (logUserName == null || logUserName.equals("")) logUserName = "Unknown"; NotificationMessage notificationMessage = new NotificationMessage("Login success:", "Authentication", logUserName, NotificationMessage.AUTHENTICATION_SUCCESS, "" + authenticatedUserName, "name"); TransactionHistoryController.getController().create(notificationMessage); if (successLoginBaseUrl != null && !URL.startsWith(successLoginBaseUrl)) { checkSuccessRedirect(request, response, URL); } else { fc.doFilter(request, response); return; } } else { if (userName != null && !userName.equals("")) { NotificationMessage notificationMessage = new NotificationMessage("Login failed:", "Authentication", userName, NotificationMessage.AUTHENTICATION_FAILED, "" + userName, "name"); TransactionHistoryController.getController().create(notificationMessage); } } } catch (Exception e) { logger.error("Error authenticating user:" + e.getMessage(), e); httpServletRequest.setAttribute("error", new Exception( "Error in authentication filter - look at the server error log (usually catalina.out) for reason but the most common one is problem connecting to the database or a faulty connection user or limited access for that account.")); httpServletResponse.sendError(500); return; } }
From source file:org.openqa.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {/*from w w w .j a v a 2s. co m*/ throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:org.apache.catalina.authenticator.AuthenticatorBase.java
/** * Register an authenticated Principal and authentication type in our * request, in the current session (if there is one), and with our * SingleSignOn valve, if there is one. Set the appropriate cookie * to be returned./*ww w . j a v a2 s.c o m*/ * * @param request The servlet request we are processing * @param response The servlet response we are generating * @param principal The authenticated Principal to be registered * @param authType The authentication type to be registered * @param username Username used to authenticate (if any) * @param password Password used to authenticate (if any) */ protected void register(HttpRequest request, HttpResponse response, Principal principal, String authType, String username, String password) { if (log.isDebugEnabled()) log.debug("Authenticated '" + principal.getName() + "' with type '" + authType + "'"); // Cache the authentication information in our request request.setAuthType(authType); request.setUserPrincipal(principal); Session session = getSession(request, false); // Cache the authentication information in our session, if any if (cache) { if (session != null) { session.setAuthType(authType); session.setPrincipal(principal); if (username != null) session.setNote(Constants.SESS_USERNAME_NOTE, username); else session.removeNote(Constants.SESS_USERNAME_NOTE); if (password != null) session.setNote(Constants.SESS_PASSWORD_NOTE, password); else session.removeNote(Constants.SESS_PASSWORD_NOTE); } } // Construct a cookie to be returned to the client if (sso == null) return; // Only create a new SSO entry if the SSO did not already set a note // for an existing entry (as it would do with subsequent requests // for DIGEST and SSL authenticated contexts) String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (ssoId == null) { // Construct a cookie to be returned to the client HttpServletResponse hres = (HttpServletResponse) response.getResponse(); ssoId = generateSessionId(); Cookie cookie = new Cookie(Constants.SINGLE_SIGN_ON_COOKIE, ssoId); cookie.setMaxAge(-1); cookie.setPath("/"); hres.addCookie(cookie); // Register this principal with our SSO valve sso.register(ssoId, principal, authType, username, password); request.setNote(Constants.REQ_SSOID_NOTE, ssoId); } else { // Update the SSO session with the latest authentication data sso.update(ssoId, principal, authType, username, password); } // Fix for Bug 10040 // Always associate a session with a new SSO reqistration. // SSO entries are only removed from the SSO registry map when // associated sessions are destroyed; if a new SSO entry is created // above for this request and the user never revisits the context, the // SSO entry will never be cleared if we don't associate the session if (session == null) session = getSession(request, true); sso.associate(ssoId, session); }
From source file:com.alfaariss.oa.util.web.CookieTool.java
/** * Set Cookie with optional extra context in application context * @param sCookie//from ww w . ja v a2 s. c o m * @param sValue * @param sExtraContext * @param oRequest * @return */ public Cookie createCookie(String sCookie, String sValue, String sExtraContext, HttpServletRequest oRequest) { assert sValue != null : "Supplied value == null"; assert oRequest != null : "Supplied request == null"; Cookie cookie = new Cookie(sCookie, sValue); if (_sCookieDomain != null) { cookie.setDomain(_sCookieDomain); _logger.debug("Created domain cookie on " + _sCookieDomain); } if (_iCookieVersion != -1) { cookie.setVersion(_iCookieVersion); _logger.debug("Setting cookie version: " + _iCookieVersion); } /* format sExtraContext */ if (sExtraContext == null) { sExtraContext = ""; } else { if (!sExtraContext.startsWith("/")) { sExtraContext = "/" + sExtraContext; } } String path = oRequest.getContextPath(); if (path != null && path.length() > 0) {//only set path if path not is empty (when hosted as server root, getContextPath() will return an empty string) cookie.setPath(path + sExtraContext);// /openaselect } else {//if no contextpath available then setting the cookie path on '/' instead of on the default path (which is for the sso cookie: /openaselect/sso) cookie.setPath("/" + sExtraContext); } cookie.setSecure(_bSecureCookie); StringBuffer sbDebug = new StringBuffer("Created '"); sbDebug.append(sCookie); sbDebug.append("' on path="); sbDebug.append(cookie.getPath()); _logger.debug(sbDebug.toString()); return cookie; }
From source file:nl.nn.adapterframework.http.rest.ApiListenerServlet.java
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /**/*from ww w . j a v a 2 s .c o m*/ * Initiate and populate messageContext */ PipeLineSessionBase messageContext = new PipeLineSessionBase(); messageContext.put(IPipeLineSession.HTTP_REQUEST_KEY, request); messageContext.put(IPipeLineSession.HTTP_RESPONSE_KEY, response); messageContext.put(IPipeLineSession.SERVLET_CONTEXT_KEY, getServletContext()); messageContext.setSecurityHandler(new HttpSecurityHandler(request)); try { String uri = request.getPathInfo(); String method = request.getMethod().toUpperCase(); log.trace("ApiListenerServlet dispatching uri [" + uri + "] and method [" + method + "]"); if (uri == null) { response.setStatus(400); log.warn("Aborting request with status [400], empty uri"); return; } if (uri.startsWith("/")) uri = uri.substring(1); if (uri.endsWith("/")) uri = uri.substring(0, uri.length() - 1); ApiDispatchConfig config = dispatcher.findConfigForUri(uri); if (config == null) { response.setStatus(404); log.trace("Aborting request with status [404], no ApiListener configured for [" + uri + "]"); return; } /** * Handle Cross-Origin Resource Sharing * TODO make this work behind loadbalancers/reverse proxies * TODO check if request ip/origin header matches allowOrigin property */ String origin = request.getHeader("Origin"); if (method.equals("OPTIONS") || origin != null) { response.setHeader("Access-Control-Allow-Origin", CorsAllowOrigin); String headers = request.getHeader("Access-Control-Request-Headers"); if (headers != null) response.setHeader("Access-Control-Allow-Headers", headers); response.setHeader("Access-Control-Expose-Headers", CorsExposeHeaders); StringBuilder methods = new StringBuilder(); for (String mtd : config.getMethods()) { methods.append(", ").append(mtd); } response.setHeader("Access-Control-Allow-Methods", methods.toString()); //Only cut off OPTIONS (aka preflight) requests if (method.equals("OPTIONS")) { response.setStatus(200); log.trace("Aborting preflight request with status [200], method [" + method + "]"); return; } } /** * Get serviceClient */ ApiListener listener = config.getApiListener(method); if (listener == null) { response.setStatus(405); log.trace("Aborting request with status [405], method [" + method + "] not allowed"); return; } log.trace("ApiListenerServlet calling service [" + listener.getName() + "]"); /** * Check authentication */ ApiPrincipal userPrincipal = null; if (listener.getAuthenticationMethod() != null) { String authorizationToken = null; Cookie authorizationCookie = null; if (listener.getAuthenticationMethod().equals("COOKIE")) { Cookie[] cookies = request.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals("authenticationToken")) { authorizationToken = cookie.getValue(); authorizationCookie = cookie; authorizationCookie.setPath("/"); } } } else if (listener.getAuthenticationMethod().equals("HEADER")) { authorizationToken = request.getHeader("Authorization"); } if (authorizationToken != null && cache.containsKey(authorizationToken)) userPrincipal = (ApiPrincipal) cache.get(authorizationToken); if (userPrincipal == null || !userPrincipal.isLoggedIn()) { cache.remove(authorizationToken); if (authorizationCookie != null) { authorizationCookie.setMaxAge(0); response.addCookie(authorizationCookie); } response.setStatus(401); log.trace("Aborting request with status [401], no (valid) credentials supplied"); return; } if (authorizationCookie != null) { authorizationCookie.setMaxAge(authTTL); response.addCookie(authorizationCookie); } userPrincipal.updateExpiry(); userPrincipal.setToken(authorizationToken); cache.put(authorizationToken, userPrincipal, authTTL); messageContext.put("authorizationToken", authorizationToken); } messageContext.put("remoteAddr", request.getRemoteAddr()); messageContext.put(IPipeLineSession.API_PRINCIPAL_KEY, userPrincipal); messageContext.put("uri", uri); /** * Evaluate preconditions */ String accept = request.getHeader("Accept"); if (accept != null && !accept.isEmpty() && !accept.equals("*/*")) { if (!listener.getProduces().equals("ANY") && !accept.contains(listener.getContentType())) { response.setStatus(406); response.getWriter().print("It appears you expected the MediaType [" + accept + "] but I only support the MediaType [" + listener.getContentType() + "] :)"); log.trace("Aborting request with status [406], client expects [" + accept + "] got [" + listener.getContentType() + "] instead"); return; } } if (request.getContentType() != null && !listener.isConsumable(request.getContentType())) { response.setStatus(415); log.trace("Aborting request with status [415], did not match consumes [" + listener.getConsumes() + "] got [" + request.getContentType() + "] instead"); return; } String etagCacheKey = ApiCacheManager.buildCacheKey(uri); log.debug("Evaluating preconditions for listener[" + listener.getName() + "] etagKey[" + etagCacheKey + "]"); if (cache.containsKey(etagCacheKey)) { String cachedEtag = (String) cache.get(etagCacheKey); log.debug("found etag value[" + cachedEtag + "] for key[" + etagCacheKey + "]"); if (method.equals("GET")) { String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && ifNoneMatch.equals(cachedEtag)) { response.setStatus(304); log.trace( "Aborting request with status [304], matched if-none-match [" + ifNoneMatch + "]"); return; } } else { String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !ifMatch.equals(cachedEtag)) { response.setStatus(412); log.trace("Aborting request with status [412], matched if-match [" + ifMatch + "] method [" + method + "]"); return; } } } messageContext.put("updateEtag", listener.getUpdateEtag()); /** * Check authorization */ //TODO: authentication implementation /** * Map uriIdentifiers into messageContext */ String patternSegments[] = listener.getUriPattern().split("/"); String uriSegments[] = uri.split("/"); int uriIdentifier = 0; for (int i = 0; i < patternSegments.length; i++) { String segment = patternSegments[i]; if (segment.startsWith("{") && segment.endsWith("}")) { String name; if (segment.equals("*")) name = "uriIdentifier_" + uriIdentifier; else name = segment.substring(1, segment.length() - 1); uriIdentifier++; log.trace("setting uriSegment [" + name + "] to [" + uriSegments[i] + "]"); messageContext.put(name, uriSegments[i]); } } /** * Map queryParameters into messageContext */ Enumeration<?> paramnames = request.getParameterNames(); while (paramnames.hasMoreElements()) { String paramname = (String) paramnames.nextElement(); String paramvalue = request.getParameter(paramname); log.trace("setting queryParameter [" + paramname + "] to [" + paramvalue + "]"); messageContext.put(paramname, paramvalue); } /** * Map multipart parts into messageContext */ if (ServletFileUpload.isMultipartContent(request)) { DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory); List<FileItem> items = servletFileUpload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // Process regular form field (input type="text|radio|checkbox|etc", select, etc). String fieldName = item.getFieldName(); String fieldValue = item.getString(); log.trace("setting multipart formField [" + fieldName + "] to [" + fieldValue + "]"); messageContext.put(fieldName, fieldValue); } else { // Process form file field (input type="file"). String fieldName = item.getFieldName(); String fieldNameName = fieldName + "Name"; String fileName = FilenameUtils.getName(item.getName()); log.trace("setting multipart formFile [" + fieldNameName + "] to [" + fileName + "]"); messageContext.put(fieldNameName, fileName); log.trace( "setting parameter [" + fieldName + "] to input stream of file [" + fileName + "]"); messageContext.put(fieldName, item.getInputStream()); } } } /** * Compile Allow header */ StringBuilder methods = new StringBuilder(); methods.append("OPTIONS, "); for (String mtd : config.getMethods()) { methods.append(mtd + ", "); } messageContext.put("allowedMethods", methods.substring(0, methods.length() - 2)); /** * Process the request through the pipeline */ String body = ""; if (!ServletFileUpload.isMultipartContent(request)) { body = Misc.streamToString(request.getInputStream(), "\n", false); } String result = listener.processRequest(null, body, messageContext); /** * Calculate an eTag over the processed result and store in cache */ if (messageContext.get("updateEtag", true)) { log.debug("calculating etags over processed result"); String cleanPattern = listener.getCleanPattern(); if (result != null && method.equals("GET")) { String eTag = ApiCacheManager.buildEtag(cleanPattern, result.hashCode()); log.debug("adding/overwriting etag with key[" + etagCacheKey + "] value[" + eTag + "]"); cache.put(etagCacheKey, eTag); response.addHeader("etag", eTag); } else { log.debug("removing etag with key[" + etagCacheKey + "]"); cache.remove(etagCacheKey); // Not only remove the eTag for the selected resources but also the collection String key = ApiCacheManager.getParentCacheKey(listener, uri); if (key != null) { log.debug("removing parent etag with key[" + key + "]"); cache.remove(key); } } } /** * Add headers */ response.addHeader("Allow", (String) messageContext.get("allowedMethods")); String contentType = listener.getContentType() + "; charset=utf-8"; if (listener.getProduces().equals("ANY")) { contentType = messageContext.get("contentType", contentType); } response.setHeader("Content-Type", contentType); /** * Check if an exitcode has been defined or if a statuscode has been added to the messageContext. */ int statusCode = messageContext.get("exitcode", 0); if (statusCode > 0) response.setStatus(statusCode); /** * Finalize the pipeline and write the result to the response */ if (result != null) response.getWriter().print(result); log.trace("ApiListenerServlet finished with statusCode [" + statusCode + "] result [" + result + "]"); } catch (Exception e) { log.warn("ApiListenerServlet caught exception, will rethrow as ServletException", e); try { response.flushBuffer(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } catch (IllegalStateException ex) { //We're only informing the end user(s), no need to catch this error... response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }
From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java
/** * Copy cookie from the proxy to the servlet client. Replaces cookie path to * local path and renames cookie to avoid collisions. *//* ww w. ja v a 2 s .c om*/ protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse, String headerValue) { List<HttpCookie> cookies = HttpCookie.parse(headerValue); String path = servletRequest.getContextPath(); // path starts with / or // is empty string path += servletRequest.getServletPath(); // servlet path starts with / // or is empty string for (HttpCookie cookie : cookies) { // set cookie name prefixed w/ a proxy value so it won't collide w/ // other cookies String proxyCookieName = getCookieNamePrefix(cookie.getName()) + cookie.getName(); Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue()); servletCookie.setComment(cookie.getComment()); servletCookie.setMaxAge((int) cookie.getMaxAge()); servletCookie.setPath(path); // set to the path of the proxy servlet // don't set cookie domain servletCookie.setSecure(cookie.getSecure()); servletCookie.setVersion(cookie.getVersion()); servletResponse.addCookie(servletCookie); } }
From source file:com.google.gsa.valve.modules.noauth.HTTPNoAuthenticationProcess.java
/** * This method simulates the authentication process against a content * source, so that every document is consider here as public. * <p>/*from w w w . java2 s . c om*/ * Creates the authentication cookie and always return 200, unless there is * any problem processing the request. * * @param request HTTP request * @param response HTTP response * @param authCookies vector that contains the authentication cookies * @param url the document url * @param creds an array of credentials for all external sources * @param id the default credential id to be retrieved from creds * @return the HTTP error code * @throws HttpException * @throws IOException */ public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies, String url, Credentials creds, String id) throws HttpException, IOException { Cookie[] cookies = null; // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; // Read cookies cookies = request.getCookies(); // Debug logger.debug("HTTP No authentication start"); // // Launch the authentication process // // Protection try { Cookie extAuthCookie = null; extAuthCookie = new Cookie("gsa_basic_noauth", ""); extAuthCookie.setValue("true"); String authCookieDomain = null; String authCookiePath = null; int authMaxAge = -1; // Cache cookie properties authCookieDomain = (request.getAttribute("authCookieDomain")).toString(); authCookiePath = (request.getAttribute("authCookiePath")).toString(); //authMaxAge try { authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge()); } catch (NumberFormatException nfe) { logger.error( "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:"); } // Set extra cookie parameters extAuthCookie.setDomain(authCookieDomain); extAuthCookie.setPath(authCookiePath); extAuthCookie.setMaxAge(authMaxAge); // Log info if (logger.isDebugEnabled()) logger.debug("Adding gsa_basic_noauth cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure()); //add sendCookies support boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue(); boolean sendCookies = false; if (isSessionEnabled) { sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue(); } if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) { response.addCookie(extAuthCookie); } //add cookie to the array authCookies.add(extAuthCookie); statusCode = HttpServletResponse.SC_OK; } catch (Exception e) { // Log error logger.error("HTTP Basic authentication failure: " + e.getMessage(), e); // Update status code statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // End of the authentication process logger.debug("HTTP No Authentication completed (" + statusCode + ")"); // Return status code return statusCode; }
From source file:org.openanzo.servlet.EncryptedTokenAuthenticator.java
/** * Perform form authentication. Called from SecurityHandler. * /*w ww .j a v a 2 s. c o m*/ * @param servletRequest * request to authenticate * @param response * response to send response data * * @return UserPrincipal if authenticated else null. * @throws IOException */ @SuppressWarnings("null") public boolean authenticate(HttpServletRequest servletRequest, HttpServletResponse response) throws IOException { // NOTE: Jetty will sometimes call this method with a null response parameter. In particular, from // the org.eclipse.jetty.Request#getUserPrincipal() method. boolean ret = false; Request request = Request.getRequest(servletRequest); String uri = request.getServletPath(); boolean protectedPath = false; for (PathSpec spec : protectedPathSpec) { if (spec.matches(uri)) { protectedPath = true; break; } } // Setup some defaults. Unfortunately, this is the only place we really get to set these up since the // Authenticator interface doesn't have an 'init'-like method. if (tokenTimeout <= 0) { tokenTimeout = 30 * DateUtils.MILLIS_PER_MINUTE; } if (tokenRefreshWindow <= 0) { tokenRefreshWindow = 5 * DateUtils.MILLIS_PER_MINUTE; } if (customTokenRefresh == null) { customTokenRefresh = Boolean.FALSE; } // Now handle the request uri = request.getPathInfo(); if (uri.endsWith(LOGIN_URI_SUFFIX)) { // Handle a request for authentication. ret = false; // We will entirely handle the request here so return false to stop processing the request. String username = request.getParameter(USERNAME_PARAMETER_NAME); String password = request.getParameter(PASSWORD_PARAMETER_NAME); if (username == null || password == null) { log.error(LogUtils.SECURITY_MARKER, "Invalid anzo_authenticate request url:{} username:{} password:{}", new Object[] { uri, username, password == null ? null : "XXXObscuredNonNullPasswordXXX" }); } AnzoPrincipal userPrincipal = null; try { userPrincipal = realm.authenticate(username, password, request); } catch (Exception e) { // No matter what sort of failure occurs in the realm we want to make sure to send the appropriate // error response or redirect. So we can't all exceptions here. log.debug(LogUtils.SECURITY_MARKER, "Failed authentication call to the realm.", e); } if (userPrincipal == null) { if (log.isDebugEnabled()) { log.debug(LogUtils.SECURITY_MARKER, "Authentication request FAILED for {}", StringUtil.printable(username)); } request.setAuthentication(null); if (response != null) { if (_formErrorPage == null || isRequestSentByXmlHttpRequest(request)) { if (log.isDebugEnabled()) { log.debug(LogUtils.SECURITY_MARKER, "Sending 403 Forbidden error due to invalid credentials for user {}", username); } response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { String redirectPath = response .encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)); log.debug(LogUtils.SECURITY_MARKER, "Sending redirect to form error page {}", redirectPath); response.setContentLength(0); response.sendRedirect(redirectPath); } } } else { // Authenticated OK if (log.isDebugEnabled()) { log.debug(LogUtils.SECURITY_MARKER, "Authentication request OK for {}", StringUtil.printable(username)); } request.setAuthentication(new BasicUserAuthorization(userPrincipal, AUTH_METHOD)); // Set the encrypted token if (response != null) { try { String token = createEncryptedToken(username, request.getRemoteAddr()); Cookie tokenCookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, token); tokenCookie.setPath("/"); response.addCookie(tokenCookie); if (isRequestSentByXmlHttpRequest(request)) { // XMLHttpRequests just want a response with the cookie, no fancy redirects or anything like that. // just send back 200 in text.(Need to send back something else firefox reports an error) response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.print(HttpServletResponse.SC_OK); out.flush(); out.close(); } else { // Redirect to the URL to user wanted to get to initially, or "/" if there isn't any such URL. // We get the URL from a query parameter in the HTTP Referer (sic) header. String referer = request.getHeader(HttpHeaders.REFERER); String redirectPath = null; if (referer != null) { HttpURI refererUri = new HttpURI(referer); MultiMap<String> queryParams = new MultiMap<String>(); refererUri.decodeQueryTo(queryParams, null); String desiredUrl = (String) queryParams.getValue(ANZO_URL_QUERY_PARAM, 0); if (desiredUrl != null) { redirectPath = desiredUrl; } } if (redirectPath == null) { redirectPath = URIUtil.addPaths(request.getContextPath(), "/"); } redirectPath = response.encodeRedirectURL(redirectPath); log.debug(LogUtils.SECURITY_MARKER, "Sending redirect to root {} after successful login request.", redirectPath); response.sendRedirect(redirectPath); } } catch (AnzoException cause) { IOException ex = new IOException("Error creating encrypted authentication token."); ex.initCause(cause); throw ex; } } } } else if (isLoginOrErrorPage(uri)) { // Don't authenticate authform or errorpage. Just let the system them out. ret = true; } else if (protectedPath) { // This is a regular request for a protected resource, so check whether there is a valid // encrypted token in the request. AnzoPrincipal userPrincipal = null; // Parse and validate the authentication token from the cookie Token token = null; long currentTime = System.currentTimeMillis(); Cookie[] cookies = request.getCookies(); Cookie tokenCookie = null; if (cookies != null) { for (Cookie cookie : cookies) { String cookieName = cookie.getName(); if (ANZO_TOKEN_COOKIE_NAME.equals(cookieName)) { tokenCookie = cookie; try { token = parseAnzoToken(cookie.getValue()); userPrincipal = validateAuthToken(token, realm, request.getRemoteAddr(), currentTime); } catch (AnzoException e) { log.debug(LogUtils.SECURITY_MARKER, "Error decrypting and parsing authentication token.", e); } break; } } } if (userPrincipal == null) { // Invalid, expired, or non-existent token ret = false; // Don't serve the resource if (log.isDebugEnabled()) { String msg = "Auth token "; if (tokenCookie == null) { msg += "MISSING"; } else { msg += "INVALID"; } log.debug(LogUtils.SECURITY_MARKER, msg + " for URL: {}", StringUtil.printable(request.getRequestURI())); } if (response != null) { Cookie cookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, ""); cookie.setPath("/"); cookie.setMaxAge(0); response.addCookie(cookie); // adding a cookie with MaxAge=0 tells the client to delete the cookie. if (_formLoginPage == null || isRequestSentByXmlHttpRequest(request)) { if (log.isDebugEnabled()) { log.debug(LogUtils.SECURITY_MARKER, "Sending 403 Forbidden error due to invalid auth token. Token: {}", token); } response.sendError(HttpServletResponse.SC_FORBIDDEN); } else { // We save the URL the user tried to access into a query parameter in the redirect to the login page. // That way the login page can send the user to the page they wanted after they finish logging in. // First we must reconstruct the URL the user accessed. String requestUrl = uri; if (request.getQueryString() != null) { requestUrl += "?" + request.getQueryString(); } requestUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + URIUtil.addPaths(request.getContextPath(), requestUrl); // Now we add the requested URL as a query parameter to the login URL MultiMap<String> loginPageUrlQueryParams = new MultiMap<String>(); loginPageUrlQueryParams.put(ANZO_URL_QUERY_PARAM, requestUrl); String loginPageUrl = URIUtil.addPaths(request.getContextPath(), _formLoginPage); try { loginPageUrl = addQueryParametersToURI(loginPageUrl, loginPageUrlQueryParams); } catch (URISyntaxException e) { log.warn(LogUtils.SECURITY_MARKER, "Error creating login redirect URL. The user's attempted URL won't be saved for use after login.", e); } String redirectPath = response.encodeRedirectURL(loginPageUrl); log.debug(LogUtils.SECURITY_MARKER, "Sending redirect to form login page {} after request without adequate credentials.", redirectPath); response.setContentLength(0); response.sendRedirect(redirectPath); } } } else { // Properly authenticated if (log.isDebugEnabled()) { log.debug(LogUtils.SECURITY_MARKER, "Auth token OK for '{}' for URL:{}", StringUtil.printable(userPrincipal.getName()), StringUtil.printable(request.getRequestURI())); } if (userPrincipal instanceof AnzoPrincipal) { request.setAttribute(SerializationConstants.authenticationURI, (userPrincipal).getUserURI()); } request.setAttribute(SerializationConstants.userPrincipal, userPrincipal); request.setAuthentication(new BasicUserAuthorization(userPrincipal, AUTH_METHOD)); ret = true; // Check if the token is older than the refresh window. If so, create a new cookie with an updated timestamp. try { if (currentTime < token.getTimestamp() || (currentTime - token.getTimestamp() >= tokenRefreshWindow)) { // if current time is less than the token's time, we'll issue a new cookie. That should only ever happen upon overflow of the number of milliseconds from the epoch. String cookieval = createEncryptedToken(token.getUsername(), token.getRemoteAddress()); Cookie newTokenCookie = new Cookie(ANZO_TOKEN_COOKIE_NAME, cookieval); newTokenCookie.setPath("/"); if (customTokenRefresh) { request.setAttribute(ANZO_REFRESH_COOKIE_ATTRIBUTE, newTokenCookie); } else { response.addCookie(newTokenCookie); } } } catch (AnzoException e) { log.error(LogUtils.SECURITY_MARKER, "Could NOT update timestamp on authentication token. Authentication session may end prematurely.", e); } } } else { // This is NOT a protected resource so just let it be served. ret = true; } log.debug(LogUtils.SECURITY_MARKER, "Returning from 'authenticate' with {} for path {}", ret, uri); return ret; }
From source file:axiom.servlet.AbstractServletClient.java
/** * Create a new session cookie.//w w w .j a v a 2 s.c o m * * @param b * @param reqtrans * @param domain * @return the session cookie */ private Cookie createSessionCookie(StringBuffer b, RequestTrans reqtrans, String domain) { b.append(Long.toString(Math.round(Math.random() * Long.MAX_VALUE) - System.currentTimeMillis(), 36)); reqtrans.setSession(b.toString()); Cookie cookie = new Cookie(sessionCookieName, reqtrans.getSession()); cookie.setPath("/"); if (domain != null) { cookie.setDomain(domain); } return cookie; }
From source file:com.tremolosecurity.proxy.filter.PostProcess.java
protected void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder, HttpResponse response, String finalURL, HttpFilterChain curChain, HttpRequestBase httpRequest) throws IOException, Exception { boolean isText; HttpEntity entity = null;// w ww .j a v a 2s .c o m try { entity = response.getEntity(); /*if (entity != null) { entity = new BufferedHttpEntity(entity); }*/ } catch (Throwable t) { throw new Exception(t); } InputStream ins = null; boolean entExists = false; if (entity == null) { resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); ins = new StringBufferInputStream(""); } else { try { ins = entity.getContent(); resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); entExists = true; } catch (IllegalStateException e) { //do nothing } } if (entExists) { org.apache.http.Header hdr = response.getFirstHeader("Content-Type"); org.apache.http.Header encoding = response.getFirstHeader("Content-Encoding"); /*if (hdr == null) { isText = false; } else { isText = response.getFirstHeader("Content-Type").getValue().startsWith("text"); if (encoding != null ) { isText = (! encoding.getValue().startsWith("gzip")) && (! encoding.getValue().startsWith("deflate")); } if (isText) { resp.setContentType(response.getFirstHeader("Content-Type").getValue()); resp.setLocale(response.getLocale()); } }*/ isText = false; try { resp.setCharacterEncoding(null); } catch (Throwable t) { //we're not doing anything } StringBuffer stmp = new StringBuffer(); if (response.getFirstHeader("Content-Type") != null) { resp.setContentType(response.getFirstHeader("Content-Type").getValue()); } if (response.getLocale() != null) { resp.setLocale(response.getLocale()); } org.apache.http.Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { org.apache.http.Header header = headers[i]; if (header.getName().equals("Content-Type")) { continue; } else if (header.getName().equals("Content-Type")) { continue; } else if (header.getName().equals("Content-Length")) { if (!header.getValue().equals("0")) { continue; } } else if (header.getName().equals("Transfer-Encoding")) { continue; } else if (header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")) { //System.out.println(header.getValue()); String cookieVal = header.getValue(); /*if (cookieVal.endsWith("HttpOnly")) { cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly")); } //System.out.println(cookieVal);*/ List<HttpCookie> cookies = HttpCookie.parse(cookieVal); Iterator<HttpCookie> it = cookies.iterator(); while (it.hasNext()) { HttpCookie cookie = it.next(); String cookieFinalName = cookie.getName(); if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) { stmp.setLength(0); stmp.append("JSESSIONID").append('-') .append(holder.getApp().getName().replaceAll(" ", "|")); cookieFinalName = stmp.toString(); } Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue()); respcookie.setComment(cookie.getComment()); if (cookie.getDomain() != null) { respcookie.setDomain(cookie.getDomain()); } if (cookie.hasExpired()) { respcookie.setMaxAge(0); } else { respcookie.setMaxAge((int) cookie.getMaxAge()); } respcookie.setPath(cookie.getPath()); respcookie.setSecure(cookie.getSecure()); respcookie.setVersion(cookie.getVersion()); resp.addCookie(respcookie); } } else if (header.getName().equals("Location")) { if (holder.isOverrideHost()) { fixRedirect(req, resp, finalURL, header); } else { resp.addHeader("Location", header.getValue()); } } else { resp.addHeader(header.getName(), header.getValue()); } } curChain.setIns(ins); curChain.setText(isText); curChain.setEntity(entity); curChain.setHttpRequestBase(httpRequest); //procData(req, resp, holder, isText, entity, ins); } else { isText = false; } }