List of usage examples for javax.servlet.http Cookie getValue
public String getValue()
From source file:io.stallion.users.UserController.java
/** * Checks the standard Stallion auth cookie, loads and validates the user, * and hydrates the current request Context user, and returns true. Returns * false if there is not cookie, or it did not represent a valid user. * * @param request//from w w w . j a va 2 s .com * @return */ public boolean checkCookieAndAuthorizeForRequest(StRequest request) { Cookie userCookie = request.getCookie(UserController.USER_COOKIE_NAME); if (userCookie == null) { return false; } return checkCookieAndAuthorizeForCookieValue(userCookie.getValue()); }
From source file:CookieReader.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { Cookie cookie = null; //Get an array of Cookies associated with this domain Cookie[] cookies = request.getCookies(); boolean hasCookies = false; if (cookies != null) hasCookies = true;//from w w w. j a v a 2s . c o m // display the name/value of each cookie response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Cookie information</title>"); out.println("</head>"); out.println("<body>"); if (hasCookies) { out.println("<h2> The name and value of each found cookie</h2>"); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; out.println("Name of cookie #" + (i + 1) + ": " + cookie.getName() + "<br>"); out.println("Value of cookie #" + (i + 1) + ": " + cookie.getValue() + "<br><br>"); } } else { out.println("<h2> This request did not include any cookies</h2>"); } out.println("</body>"); out.println("</html>"); out.close(); }
From source file:MyServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { Cookie cookie = null; //Get an array of Cookies associated with this domain Cookie[] cookies = request.getCookies(); boolean hasCookies = false; if (cookies != null) hasCookies = true;/*from www. j av a 2s . c o m*/ // display the name/value of each cookie response.setContentType("text/html"); java.io.PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Cookie information</title>"); out.println("</head>"); out.println("<body>"); if (hasCookies) { out.println("<h2> The name and value of each found cookie</h2>"); for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; out.println("Name of cookie #" + (i + 1) + ": " + cookie.getName() + "<br>"); out.println("Value of cookie #" + (i + 1) + ": " + cookie.getValue() + "<br><br>"); } } else { out.println("<h2> This request did not include any cookies</h2>"); } out.println("</body>"); out.println("</html>"); out.close(); }
From source file:jp.co.opentone.bsol.framework.web.view.util.ViewHelper.java
/** * Cookie?????./* w w w . j a v a2 s . c om*/ * @param key * ?? * @return ?. ???null */ public String getCookieValue(String key) { String value = null; Cookie[] cookies = ((HttpServletRequest) getExternalContext().getRequest()).getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getName() != null && cookie.getName().equals(key)) { value = cookie.getValue(); } } } return value; }
From source file:com.qut.middleware.spep.filter.SPEPFilter.java
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { if (!(servletRequest instanceof HttpServletRequest)) { throw new ServletException(Messages.getString("SPEPFilter.0")); //$NON-NLS-1$ }//from w w w . ja va 2 s. c o m if (!(servletResponse instanceof HttpServletResponse)) { throw new ServletException(Messages.getString("SPEPFilter.1")); //$NON-NLS-1$ } HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String resource, decodedResource, requested, redirectURL; URL serviceHost; ServletContext spepContext = this.filterConfig.getServletContext().getContext(this.spepContextName); // Get servlet context. if (spepContext == null) { throw new ServletException(Messages.getString("SPEPFilter.2") + " " + this.spepContextName); //$NON-NLS-1$ //$NON-NLS-2$ } // Establish SPEPProxy object. SPEPProxy spep; try { spep = Initializer.init(spepContext); } catch (Exception e) { this.logger.error( "Unable to process request to acces resource, SPEP is not responding, check cross context configuration is enabled \n" + e.getLocalizedMessage()); throw new ServletException(Messages.getString("SPEPFilter.3"), e); //$NON-NLS-1$ } // Ensure SPEP startup. if (!spep.isStarted()) { // Don't allow anything to occur if SPEP hasn't started correctly. this.logger.error("Unable to process request to acces resource, SPEP is not initialized correcty "); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw new ServletException(Messages.getString("SPEPFilter.4")); //$NON-NLS-1$ } // Get SPEP cookie. Cookie spepCookie = null; Cookie globalESOECookie = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(spep.getTokenName())) { spepCookie = cookie; this.logger.debug("Located spep cookie with value of " + spepCookie.getValue()); } if (cookie.getName().equals(spep.getEsoeGlobalTokenName())) { globalESOECookie = cookie; this.logger .debug("Located globalESOECookie cookie with value of " + globalESOECookie.getValue()); } } } // value for re-determining session status after Authz request boolean validSession = false; // Check SPEP session is valid. if (spepCookie != null) { String sessionID = spepCookie.getValue(); this.logger.info("Attempting to retrieve data for session with ID of " + sessionID); PrincipalSession PrincipalSession = spep.verifySession(sessionID); if (PrincipalSession != null) { this.logger.info("Located session with ID of " + sessionID); if (request.getSession().getAttribute(ATTRIBUTES) == null) { // over write with new data if it exists WORMHashMap<String, List<Object>> attributeMap = new WORMHashMap<String, List<Object>>(); attributeMap.putAll(PrincipalSession.getAttributes()); attributeMap.close(); request.getSession().setAttribute(ATTRIBUTES, attributeMap); request.getSession().setAttribute(SPEP_SESSIONID, sessionID); } /* * This section of code is critical, we must pass the PEP an exact representation of what the user is * attempting to access additionally the PEP expects that the string is not in encoded form as it will * do exact matching, so we decode before passing our request to it. */ resource = request.getRequestURI(); if (request.getQueryString() != null) resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$ decodedResource = decode(resource); SPEPProxy.decision authzDecision = spep.makeAuthzDecision(sessionID, decodedResource); // the authz processor may destroy the session if the PDP determines that the client // session is no longer valid, so we have to check it again if ((PrincipalSession = spep.verifySession(sessionID)) != null) validSession = true; if (validSession) { if (authzDecision == SPEPProxy.decision.permit) { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was permissable"); chain.doFilter(request, response); return; } else if (authzDecision == SPEPProxy.decision.deny) { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was denied, forcing response of" + HttpServletResponse.SC_FORBIDDEN); response.setStatus(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN); response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } else if (authzDecision == SPEPProxy.decision.error) { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was in error, forcing response of" + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw new ServletException(Messages.getString("SPEPFilter.6")); //$NON-NLS-1$ } else { this.logger.info("PDP advised for session ID of " + sessionID + " that access to resource " + decodedResource + " was undetermined, forcing response of" + HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); throw new ServletException(Messages.getString("SPEPFilter.7")); //$NON-NLS-1$ } } } /* Clear the local session object the supplied request is invalid */ this.logger.debug("Invalidating session for ID of " + sessionID); request.getSession().invalidate(); } /* * If we get to this stage, the user has not got a session established with this SPEP. We proceed to clear the * cookies configured by the SPEP to be cleared upon logout, since this is potentially the first time they have * come back to the SPEP since logging out. */ List<Cookie> clearCookies = new Vector<Cookie>(); if (cookies != null) { for (Cookie cookie : cookies) { if (spep.getLogoutClearCookies() != null) { for (Cookie clearCookie : spep.getLogoutClearCookies()) { if (cookie.getName().equalsIgnoreCase(clearCookie.getName())) { Cookie clearCookieCloneInsecure = (Cookie) clearCookie.clone(); clearCookieCloneInsecure.setMaxAge(0); clearCookieCloneInsecure.setSecure(false); clearCookies.add(clearCookieCloneInsecure); // Don't need to process the inner loop again for this cookie. break; } } } } } /* Add the cookies to be cleared into the response object. */ for (Cookie c : clearCookies) response.addCookie(c); /* * Remove any principal object details which may be in the session, this state can occur if the user has removed * their spepSession cookie but retained their jsessionid cookie */ request.getSession().removeAttribute(ATTRIBUTES); /* * At this stage a determination needs to be made about allowing the request to pass SPEP without being hindered * due to lazy session initialization being configured if it isn't or we won't allow the request to pass for the * logical reasons below they will be forced to authenticate. */ if (spep.isLazyInit()) { this.logger.info( "Lazy init is enabled on this SPEP instance, determining if request should be interrogated by SPEP"); /* * We are being lazy in starting sessions, determine if user has already authenticated with an IDP (the * ESOE), if so we enforce a session (value is not important just that the cookie exists), if not figure out * if user is accessing something that has been configured to force a session to be established before it is * accessible */ if (globalESOECookie == null) { this.logger.debug("globalESOECookie was not set for this request"); boolean matchedLazyInitResource = false; resource = request.getRequestURI(); if (request.getQueryString() != null) resource = resource + "?" + request.getQueryString(); //$NON-NLS-1$ decodedResource = decode(resource); for (String lazyInitResource : spep.getLazyInitResources()) { if (decodedResource.matches(lazyInitResource)) { matchedLazyInitResource = true; this.logger.info("Lazy session init attempt matched initialization query of " + lazyInitResource + " from request of " + decodedResource); } else this.logger.debug("Lazy session init attempt failed to match initialization query of " + lazyInitResource + " from request of " + decodedResource); } // If we still have no reason to engage spep functionality for this request let the request pass if (matchedLazyInitResource) { if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.deny)) { this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource + " could be determined due to lazyInit, forwarding request to application"); chain.doFilter(request, response); return; } } else { if (spep.getLazyInitDefaultAction().equals(SPEPProxy.defaultAction.permit)) { this.logger.info("No reason to invoke SPEP for access to resource " + decodedResource + " could be determined due to lazyInit, forwarding request to application"); chain.doFilter(request, response); return; } } } } /* * All attempts to provide resource access have failed, invoke SPEP to provide secure session establishment * Current request is B64 encoded and appended to request for SPEP to redirect users back to content dynamically */ this.logger.debug("Failed all avenues to provide access to content"); if (request.getQueryString() != null) requested = request.getRequestURI() + "?" + request.getQueryString(); else requested = request.getRequestURI(); /* * Determine if the request was directed to the service URL, if so redirect to that point. If not redirect to * the local node. */ serviceHost = new URL(spep.getServiceHost()); String ssoRedirect = spep.getSsoRedirect(); String timestampParameter; if (ssoRedirect.indexOf('?') > -1) { timestampParameter = "&ts=" + System.currentTimeMillis(); } else { timestampParameter = "?ts=" + System.currentTimeMillis(); } if (request.getServerName().equals(serviceHost.getHost())) { /* Ensures that SSL offloading in Layer 7 environments is correctly handled */ requested = spep.getServiceHost() + requested; String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes())); redirectURL = MessageFormat.format(spep.getServiceHost() + spep.getSsoRedirect(), new Object[] { base64RequestURI + timestampParameter }); } else { String base64RequestURI = new String(Base64.encodeBase64(requested.getBytes())); redirectURL = MessageFormat.format(spep.getSsoRedirect(), new Object[] { base64RequestURI + timestampParameter }); } this.logger.debug("Redirecting to " + redirectURL + " to establish secure session"); response.sendRedirect(redirectURL); }
From source file:com.google.gsa.valve.modules.ldap.LDAPSSO.java
/** * Sets the LDAP authentication cookie// w ww . j a v a2 s.c o m * * @return the LDAP authentication cookie */ public Cookie settingCookie() { // Instantiate a new cookie Cookie extAuthCookie = new Cookie(SSO_COOKIE_NAME, "true"); String authCookieDomain = null; String authCookiePath = null; // Cache cookie properties authCookieDomain = valveConf.getAuthCookieDomain(); authCookiePath = valveConf.getAuthCookiePath(); // Set extra cookie parameters extAuthCookie.setDomain(authCookieDomain); extAuthCookie.setPath(authCookiePath); extAuthCookie.setMaxAge(authMaxAge); // Log info logger.debug("Adding cookie: " + extAuthCookie.getName() + ":" + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain() + ":" + extAuthCookie.getSecure()); return extAuthCookie; }
From source file:org.apache.solr.client.solrj.impl.BasicHttpSolrClientTest.java
/** * Set cookies via interceptor// ww w . j av a2 s. c om * Change the request via an interceptor * Ensure cookies are actually set and that request is actually changed */ @Test public void testInterceptors() { DebugServlet.clear(); HttpClientUtil.addRequestInterceptor(changeRequestInterceptor); HttpClientUtil.addRequestInterceptor(cookieSettingRequestInterceptor); final String clientUrl = jetty.getBaseUrl().toString() + "/debug/foo"; try (HttpSolrClient server = getHttpSolrClient(clientUrl)) { SolrQuery q = new SolrQuery("foo"); q.setParam("a", "\u1234"); try { server.query(q, random().nextBoolean() ? METHOD.POST : METHOD.GET); } catch (Throwable t) { } // Assert cookies from UseContextCallback assertNotNull(DebugServlet.cookies); boolean foundCookie = false; for (javax.servlet.http.Cookie cookie : DebugServlet.cookies) { if (cookieName.equals(cookie.getName()) && cookieValue.equals(cookie.getValue())) { foundCookie = true; break; } } assertTrue(foundCookie); // Assert request changes by ChangeRequestCallback assertEquals("\u1234", DebugServlet.parameters.get("a")[0]); assertEquals("\u4321", DebugServlet.parameters.get("b")[0]); } catch (IOException ex) { throw new RuntimeException(ex); } finally { HttpClientUtil.removeRequestInterceptor(changeRequestInterceptor); HttpClientUtil.removeRequestInterceptor(cookieSettingRequestInterceptor); } }
From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTests.java
@Test public void buildRequestCookiesMulti() { webRequest.setAdditionalHeader("Cookie", "name=value; name2=value2"); MockHttpServletRequest actualRequest = requestBuilder.buildRequest(servletContext); Cookie[] cookies = actualRequest.getCookies(); assertThat(cookies.length, equalTo(2)); Cookie cookie = cookies[0];// w ww .j a v a 2s . c o m assertThat(cookie.getName(), equalTo("name")); assertThat(cookie.getValue(), equalTo("value")); cookie = cookies[1]; assertThat(cookie.getName(), equalTo("name2")); assertThat(cookie.getValue(), equalTo("value2")); }
From source file:org.springframework.test.web.servlet.htmlunit.HtmlUnitRequestBuilderTests.java
@Test public void mergeCookie() throws Exception { String cookieName = "PARENT"; String cookieValue = "VALUE"; MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new HelloController()) .defaultRequest(get("/").cookie(new Cookie(cookieName, cookieValue))).build(); Cookie[] cookies = mockMvc.perform(requestBuilder).andReturn().getRequest().getCookies(); assertThat(cookies, notNullValue()); assertThat(cookies.length, equalTo(1)); Cookie cookie = cookies[0];/*from ww w. ja v a2s .c o m*/ assertThat(cookie.getName(), equalTo(cookieName)); assertThat(cookie.getValue(), equalTo(cookieValue)); }