List of usage examples for javax.servlet.http Cookie getPath
public String getPath()
From source file:gov.nih.nci.ncicb.cadsr.admintool.struts.action.BaseDispatchAction.java
protected ActionForward dispatchMethod(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String name) throws Exception { String user = null;//from w w w . ja v a2s. co m Cookie[] cookieArray = request.getCookies(); if (cookieArray != null) { for (int i = 0; i < cookieArray.length; i++) { Cookie c = cookieArray[i]; if (c.getName().equals("ADMIN_TOOL_USER")) { user = c.getValue(); System.out.println("Reading username from cookie :" + user); System.out.println("Domain: " + c.getDomain()); System.out.println("Path: " + c.getPath()); } } } if (user == null) { return mapping.findForward("login"); } return super.dispatchMethod(mapping, form, request, response, name); }
From source file:gov.nih.nci.ncicb.cadsr.admintool.struts.action.BaseAction.java
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String user = null;//w ww . j a v a2 s . c o m Cookie[] cookieArray = request.getCookies(); if (cookieArray != null) { for (int i = 0; i < cookieArray.length; i++) { Cookie c = cookieArray[i]; if (c.getName().equals("ADMIN_TOOL_USER")) { user = c.getValue(); System.out.println("Reading username from cookie :" + user); System.out.println("Domain: " + c.getDomain()); System.out.println("Path: " + c.getPath()); } } } if (user == null) { return mapping.findForward("login"); } return executeAction(mapping, form, request, response); }
From source file:eu.eidas.node.AbstractNodeServlet.java
/** * Sets HTTPOnly Header on the session to prevent cookies from being accessed through * client-side script./*www . ja v a 2s .c o m*/ * * @param renewSession indicates that the session cookie will be renewed */ protected final void setHTTPOnlyHeaderToSession(final boolean renewSession, HttpServletRequest request, HttpServletResponse response) { if (request != null && request.getSession(false) != null) { // Renewing the session if necessary String currentSession = null; String messageLog = null; if (renewSession) { currentSession = sessionIdRegenerationInWebApp(request); messageLog = "http session Renewed : {}"; } else { currentSession = request.getSession().getId(); messageLog = "http session obtained from request : {}"; } MDC.put(LoggingMarkerMDC.MDC_SESSIONID, currentSession); getLogger().info(LoggingMarkerMDC.SECURITY_SUCCESS, messageLog, currentSession); // changing session cookie to http only cookie if (request.getCookies() != null && request.isRequestedSessionIdFromCookie()) { //Session Id requested by the client, obtained from the cookie final String requestedSessionId = request.getRequestedSessionId(); for (Cookie cookie : request.getCookies()) { getLogger().debug("Treating cookie [domain][path][name][value] : [{}][{}][{}][{}]", cookie.getName(), cookie.getPath(), cookie.getName(), cookie.getValue()); if (currentSession.equals(requestedSessionId)) { // Removes old version boolean isSecure = request.isSecure(); getLogger().debug("Cookie==session : Remove and replacing with HttpOnly {}", cookie.toString()); getLogger().debug("Is using SSL?", isSecure); //TODO: when migrating to servlet 3, use the cookie interface calls below instead of writing the http header // //NOSONAR cookie.setMaxAge(0); //NOSONAR cookie.setPath(getServletContext().getContextPath()); //NOSONAR cookie.setDomain(request.getServerName()); //NOSONAR cookie.setSecure(isSecure); //NOSONAR cookie.setHttpOnly(true); //NOSONAR response.addCookie(cookie); // Create new one httpOnly StringBuilder httpOnlyCookie = new StringBuilder(cookie.getName()) .append(EIDASValues.EQUAL.toString()).append(cookie.getValue()) .append(EIDASValues.SEMICOLON.toString()).append(" ") .append(EIDASValues.DOMAIN.toString()).append(EIDASValues.EQUAL.toString()) .append(request.getServerName()).append(EIDASValues.SEMICOLON.toString()) .append(" ").append(EIDASValues.PATH.toString()) .append(EIDASValues.EQUAL.toString()).append(getServletContext().getContextPath()) .append(EIDASValues.SEMICOLON.toString()).append(" ") .append(EIDASValues.HTTP_ONLY.toString()).append(EIDASValues.SEMICOLON.toString()) .append(isSecure ? EIDASValues.SECURE.toString() : ""); response.setHeader(EIDASValues.SETCOOKIE.toString(), httpOnlyCookie.toString()); } } } //cookie _csrf // request.setAttribute("_csrf_header", "X-CSRF-TOKEN"); // UUID idOne = UUID.randomUUID(); // LOG.info("generate csrf id="+idOne); // request.setAttribute("_csrf", idOne); response.setHeader("_csrf_header", "X-CSRF-TOKEN"); UUID idOne = UUID.randomUUID(); UUID idTwo = UUID.randomUUID(); getLogger().info("generate csrf id1=" + idOne + " id2=" + idTwo); Cookie gato = new Cookie("_csrf", idOne.toString()); response.addCookie(gato); response.setHeader("X-CSRF-TOKEN", idTwo.toString()); } else { getLogger().warn(LoggingMarkerMDC.SECURITY_FAILURE, "Request or Session is null !"); } }
From source file:AIR.Common.Web.Session.MultiValueCookie.java
public MultiValueCookie(Cookie cookie) { this._name = cookie.getName(); //Shiva: we can limit the code to the else part rather than have //the "if" part as well. The if part is there just for safety. if (StringUtils.isEmpty(cookie.getPath())) this._path = Server.getContextPath(); else/* ww w .j a v a2 s. com*/ this._path = cookie.getPath(); this._comment = cookie.getComment(); this._domain = cookie.getDomain(); this._isSecure = cookie.getSecure(); this._encodedValue = cookie.getValue(); this._cookie = cookie; deserializeCookieValue(); }
From source file:com.acc.storefront.security.cookie.EnhancedCookieGenerator.java
@Override public void addCookie(final HttpServletResponse response, final String cookieValue) { super.addCookie(new HttpServletResponseWrapper(response) { @Override/*from w w w . java 2s.c o m*/ public void addCookie(final Cookie cookie) { setEnhancedCookiePath(cookie); if (isHttpOnly()) { // Custom code to write the cookie including the httpOnly flag final StringBuffer headerBuffer = new StringBuffer(100); ServerCookie.appendCookieValue(headerBuffer, cookie.getVersion(), cookie.getName(), cookie.getValue(), cookie.getPath(), cookie.getDomain(), cookie.getComment(), cookie.getMaxAge(), cookie.getSecure(), true); response.addHeader(HEADER_COOKIE, headerBuffer.toString()); } else { // Write the cookie as normal super.addCookie(cookie); } } }, cookieValue); }
From source file:m.c.m.proxyma.rewrite.CookieRewriteEngineTest.java
public void testMasquerade_Unmasquerade_Cookie() throws NullArgumentException, IllegalArgumentException, UnsupportedEncodingException { System.out.println("masquerade/unmasqueradeCookie"); ProxymaFacade proxyma = new ProxymaFacade(); ProxymaContext context = proxyma.getContextByName("default"); ProxyFolderBean folder1 = proxyma.createNewProxyFolder("host1", "http://www.google.com/it", context); ProxyFolderBean folder2 = proxyma.createNewProxyFolder("host2", "https://www.apple.com/en", context); ProxymaResource aResource = proxyma.createNewResource(request, response, context); aResource.setProxymaRootURI("http://localhost:8080/proxyma"); aResource.setProxyFolder(folder1);//from w ww . j av a 2 s.c o m CookieRewriteEngine instance = new CookieRewriteEngine(context); Cookie theCookie = new Cookie("cookie1", "Value1"); theCookie.setDomain("google.com"); theCookie.setPath("/it/pippo"); instance.masqueradeCookie(theCookie, aResource); String expected = "localhost"; assertEquals(expected, theCookie.getDomain()); expected = "/proxyma/host1/pippo"; assertEquals(expected, theCookie.getPath()); expected = CookieRewriteEngine.PROXYMA_REWRITTEN_HEADER + "Value1"; assertEquals(expected, theCookie.getValue()); instance.unmasqueradeCookie(theCookie); expected = "Value1"; assertEquals(expected, theCookie.getValue()); theCookie = new Cookie("cookie2", "Value2"); instance.masqueradeCookie(theCookie, aResource); expected = "localhost"; assertEquals(expected, theCookie.getDomain()); expected = "/proxyma/host1"; assertEquals(expected, theCookie.getPath()); expected = CookieRewriteEngine.PROXYMA_REWRITTEN_HEADER + "Value2"; assertEquals(expected, theCookie.getValue()); instance.unmasqueradeCookie(theCookie); expected = "Value2"; assertEquals(expected, theCookie.getValue()); proxyma.removeProxyFolder(folder2, context); proxyma.removeProxyFolder(folder1, context); }
From source file:com.hypersocket.netty.HttpResponseServletWrapper.java
@Override public void addCookie(Cookie cookie) { StringBuffer cookieHeader = new StringBuffer(); cookieHeader.append(cookie.getName()); cookieHeader.append("="); cookieHeader.append(cookie.getValue()); if (cookie.getPath() != null) { cookieHeader.append("; Path="); cookieHeader.append(cookie.getPath()); }//w w w . j ava 2 s. c o m if (cookie.getDomain() != null) { cookieHeader.append("; Domain="); cookieHeader.append(cookie.getDomain()); } if (cookie.getMaxAge() > 0) { cookieHeader.append("; Max-Age="); cookieHeader.append(cookie.getMaxAge()); /** * This breaks IE when date of server and browser do not match */ cookieHeader.append("; Expires="); if (cookie.getMaxAge() == 0) { cookieHeader.append(DateUtils.formatDate(new Date(10000), DateUtils.PATTERN_RFC1036)); } else { cookieHeader.append( DateUtils.formatDate(new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L), DateUtils.PATTERN_RFC1036)); } } if (cookie.getSecure()) { cookieHeader.append("; Secure"); } /** * Make sure we are not adding duplicate cookies */ for (Entry<String, String> entry : response.getHeaders()) { if (entry.getKey().equals("Set-Cookie") && entry.getValue().equals(cookieHeader.toString())) { return; } } addHeader("Set-Cookie", cookieHeader.toString()); }
From source file:com.versatus.jwebshield.filter.SecurityTokenFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; HttpServletResponse httpRes = (HttpServletResponse) response; UrlExclusionList exclList = (UrlExclusionList) request.getServletContext() .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME); logger.debug("doFilter: request from IP address=" + httpReq.getRemoteAddr()); if (httpReq.getSession(false) == null) { chain.doFilter(request, response); return;/*from w w w . j a v a 2 s .c o m*/ } logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list " + exclList.getExclusionMap()); try { if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) { chain.doFilter(request, response); return; } } catch (Exception e) { logger.error("doFilter", e); } // Check the user session for the salt cache, if none is present we // create one Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME); if (csrfPreventionSaltCache == null) { if (tokenTimeout == -1) { csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000).build(); } else { csrfPreventionSaltCache = CacheBuilder.newBuilder().maximumSize(1000) .expireAfterAccess(tokenTimeout, TimeUnit.SECONDS).build(); } httpReq.getSession().setAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME, csrfPreventionSaltCache); String nameSalt = RandomStringUtils.random(10, 0, 0, true, true, null, new SecureRandom()); httpReq.getSession().setAttribute(SecurityConstant.SALT_PARAM_NAME, nameSalt); } // Generate the salt and store it in the users cache String salt = RandomStringUtils.random(20, 0, 0, true, true, null, new SecureRandom()); String saltNameAttr = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME); SecurityInfo si = new SecurityInfo(saltNameAttr, salt); if (SecurityTokenFilter.checkReferer) { String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer")); logger.debug("doFilter: refHeader=" + refHeader); if (StringUtils.isNotBlank(refHeader)) { try { URL refUrl = new URL(refHeader); refHeader = refUrl.getHost(); } catch (MalformedURLException mex) { logger.debug("doFilter: parsing referer header failed", mex); } } si.setRefererHost(refHeader); } logger.debug("doFilter: si=" + si.toString()); csrfPreventionSaltCache.put(si, si); // Add the salt to the current request so it can be used // by the page rendered in this request httpReq.setAttribute(SecurityConstant.SALT_ATTR_NAME, si); // set CSRF cookie HttpSession session = httpReq.getSession(false); if (session != null && StringUtils.isNotBlank(csrfCookieName)) { if (logger.isDebugEnabled()) { Cookie[] cookies = httpReq.getCookies(); // boolean cookiePresent = false; for (Cookie c : cookies) { String name = c.getName(); logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value=" + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly=" + c.isHttpOnly()); // if (csrfCookieName.equals(name)) { // cookiePresent = true; // break; // } } } // if (!cookiePresent) { byte[] hashSalt = new byte[32]; SecureRandom sr = new SecureRandom(); sr.nextBytes(hashSalt); String csrfHash = RandomStringUtils.random(64, 0, 0, true, true, null, sr); Cookie c = new Cookie(csrfCookieName, csrfHash); c.setMaxAge(1800); c.setSecure(false); c.setPath(httpReq.getContextPath()); c.setHttpOnly(false); httpRes.addCookie(c); // session.setAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM, // hashStr); // } } chain.doFilter(request, response); }
From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java
@Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException { // debug informations log.debug("doGet"); log.debug("context path: " + request.getContextPath()); log.debug("character encoding: " + request.getCharacterEncoding()); log.debug("content length: " + request.getContentLength()); log.debug("content type: " + request.getContentType()); log.debug("local addr: " + request.getLocalAddr()); log.debug("local name: " + request.getLocalName()); log.debug("local port: " + request.getLocalPort()); log.debug("method: " + request.getMethod()); log.debug("path info: " + request.getPathInfo()); log.debug("path translated: " + request.getPathTranslated()); log.debug("protocol: " + request.getProtocol()); log.debug("query string: " + request.getQueryString()); log.debug("requested session id: " + request.getRequestedSessionId()); log.debug("Host header: " + request.getServerName()); log.debug("servlet path: " + request.getServletPath()); log.debug("request URI: " + request.getRequestURI()); @SuppressWarnings("unchecked") final Enumeration<String> header_names = request.getHeaderNames(); while (header_names.hasMoreElements()) { final String header_name = header_names.nextElement(); log.debug("header name: " + header_name); @SuppressWarnings("unchecked") final Enumeration<String> header_values = request.getHeaders(header_name); while (header_values.hasMoreElements()) log.debug(" " + header_name + " => " + header_values.nextElement()); }/*from ww w . j ava 2s .c o m*/ if (request.getCookies() != null) for (Cookie cookie : request.getCookies()) { log.debug("cookie:"); log.debug("cookie comment: " + cookie.getComment()); log.debug("cookie domain: " + cookie.getDomain()); log.debug("cookie max age: " + cookie.getMaxAge()); log.debug("cookie name: " + cookie.getName()); log.debug("cookie path: " + cookie.getPath()); log.debug("cookie value: " + cookie.getValue()); log.debug("cookie version: " + cookie.getVersion()); log.debug("cookie secure: " + cookie.getSecure()); } @SuppressWarnings("unchecked") final Enumeration<String> parameter_names = request.getParameterNames(); while (parameter_names.hasMoreElements()) { final String parameter_name = parameter_names.nextElement(); log.debug("parameter name: " + parameter_name); final String[] parameter_values = request.getParameterValues(parameter_name); for (final String parameter_value : parameter_values) log.debug(" " + parameter_name + " => " + parameter_value); } // parse request String target_scheme = null; String target_host; int target_port; // request.getPathInfo() is url decoded final String[] path_info_parts = request.getPathInfo().split("/"); if (path_info_parts.length >= 2) target_scheme = path_info_parts[1]; if (path_info_parts.length >= 3) { target_host = path_info_parts[2]; try { if (path_info_parts.length >= 4) target_port = new Integer(path_info_parts[3]); else target_port = 80; } catch (final NumberFormatException ex) { log.warn(ex); target_port = 80; } } else { target_scheme = "http"; target_host = "www.google.com"; target_port = 80; } log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port); // create forwarding request final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port); final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection(); // be transparent for accept-language headers @SuppressWarnings("unchecked") final Enumeration<String> accepted_languages = request.getHeaders("accept-language"); while (accepted_languages.hasMoreElements()) target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement()); // be transparent for accepted headers @SuppressWarnings("unchecked") final Enumeration<String> accepted_content = request.getHeaders("accept"); while (accepted_content.hasMoreElements()) target_connection.setRequestProperty("Accept", accepted_content.nextElement()); }
From source file:com.meltmedia.cadmium.servlets.jersey.StatusService.java
@GET @Path("/health") @Produces("text/plain") public String health(@Context HttpServletRequest request) { StringBuilder builder = new StringBuilder(); builder.append("Server: " + request.getServerName() + "\n"); builder.append("Scheme: " + request.getScheme() + "\n"); builder.append("Port: " + request.getServerPort() + "\n"); builder.append("ContextPath: " + request.getContextPath() + "\n"); builder.append("ServletPath: " + request.getServletPath() + "\n"); builder.append("Uri: " + request.getRequestURI() + "\n"); builder.append("Query: " + request.getQueryString() + "\n"); Enumeration<?> headerNames = request.getHeaderNames(); builder.append("Headers:\n"); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); Enumeration<?> headers = request.getHeaders(name); builder.append(" '" + name + "':\n"); while (headers.hasMoreElements()) { String headerValue = (String) headers.nextElement(); builder.append(" -" + headerValue + "\n"); }/* w w w . j av a 2s . co m*/ } if (request.getCookies() != null) { builder.append("Cookies:\n"); for (Cookie cookie : request.getCookies()) { builder.append(" '" + cookie.getName() + "':\n"); builder.append(" value: " + cookie.getValue() + "\n"); builder.append(" domain: " + cookie.getDomain() + "\n"); builder.append(" path: " + cookie.getPath() + "\n"); builder.append(" maxAge: " + cookie.getMaxAge() + "\n"); builder.append(" version: " + cookie.getVersion() + "\n"); builder.append(" comment: " + cookie.getComment() + "\n"); builder.append(" secure: " + cookie.getSecure() + "\n"); } } return builder.toString(); }