List of usage examples for javax.servlet.http Cookie Cookie
public Cookie(String name, String value)
From source file:RequestUtil.java
/** * Parse a cookie header into an array of cookies according to RFC 2109. * //from ww w . java2s.c o m * @param header * Value of an HTTP "Cookie" header */ public static Cookie[] parseCookieHeader(String header) { if ((header == null) || (header.length() < 1)) return (new Cookie[0]); ArrayList cookies = new ArrayList(); while (header.length() > 0) { int semicolon = header.indexOf(';'); if (semicolon < 0) semicolon = header.length(); if (semicolon == 0) break; String token = header.substring(0, semicolon); if (semicolon < header.length()) header = header.substring(semicolon + 1); else header = ""; try { int equals = token.indexOf('='); if (equals > 0) { String name = token.substring(0, equals).trim(); String value = token.substring(equals + 1).trim(); cookies.add(new Cookie(name, value)); } } catch (Throwable e) { ; } } return ((Cookie[]) cookies.toArray(new Cookie[cookies.size()])); }
From source file:org.apache.archiva.redback.integration.util.AutoLoginCookies.java
private static Cookie createCookie(String cookieName, String value, String domain, String path, HttpServletRequest httpRequest) { Cookie cookie = new Cookie(cookieName, value); if (domain != null) { cookie.setDomain(domain);//from www .ja v a2s . com } if (path != null) { cookie.setPath(path); } else { // default to the context path, otherwise you get /security and such in some places cookie.setPath(getWebappContext(httpRequest)); } return cookie; }
From source file:com.google.gsa.valve.modules.ldap.LDAPUniqueCreds.java
/** * Sets the LDAP authentication cookie// w w w .j a v a 2s . c om * * @return the LDAP authentication cookie */ public Cookie settingCookie() { // Instantiate a new cookie Cookie extAuthCookie = new Cookie("gsa_ad_auth", "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:com.google.identitytoolkit.GitkitClientTest.java
public void testGetOobCodeInvalidCaptchaCode() throws Exception { Cookie[] gitkitCookie = { new Cookie("gtoken", "fake-token") }; HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class); when(mockRequest.getCookies()).thenReturn(gitkitCookie); when(mockRequest.getParameter("action")).thenReturn("resetPassword"); when(mockRequest.getParameter("email")).thenReturn("1111@example.com"); when(mockRequest.getParameter("challenge")).thenReturn("what is the number"); when(mockRequest.getParameter("response")).thenReturn("8888"); when(mockRequest.getRemoteUser()).thenReturn("1.1.1.1"); String expectedApiUrl = GitkitClient.GITKIT_API_BASE + "getOobConfirmationCode"; when(mockSender.post(eq(expectedApiUrl), anyString(), eq(headers))) .thenReturn("{ \"error\": { \"code\": \"4xx\", \"message\": \"CAPTCHA_CHECK_FAILED\" }}"); GitkitClient.OobResponse oobResponse = gitkitClient.getOobResponse(mockRequest); // the client collapses the error message down to a simple error:value assertEquals("{\"error\": \"CAPTCHA_CHECK_FAILED\" }", oobResponse.getResponseBody()); }
From source file:edu.hm.muse.controller.Logincontroller.java
@RequestMapping(value = "/adminlogin.secu", method = RequestMethod.POST) public ModelAndView doAdminLogin(@RequestParam(value = "mpwd", required = false) String mpwd, @RequestParam(value = "csrftoken", required = false) String csrfParam, HttpServletResponse response, HttpSession session) {/* w w w .j av a 2 s .c o m*/ if (null == mpwd || mpwd.isEmpty()) { throw new SuperFatalAndReallyAnnoyingException( "I can not process, because the requestparam mpwd is empty or null or something like this"); } String sql = "select count (*) from M_ADMIN where mpwd = ?"; try { String digest = calculateSHA256(new ByteArrayInputStream(mpwd.getBytes("UTF8"))); int res = 0; res = jdbcTemplate.queryForInt(sql, new Object[] { digest }, new int[] { Types.VARCHAR }); Integer csrfTokenSess = (Integer) session.getAttribute("csrftoken"); if (res != 0 && csrfParam != null && !csrfParam.isEmpty() && csrfTokenSess != null) { Integer csrfParamToken = Integer.parseInt(csrfParam); if (csrfParamToken.intValue() == csrfTokenSess.intValue()) { SecureRandom random = new SecureRandom(); int token = random.nextInt(); session.setAttribute("user", "admin"); session.setAttribute("login", true); session.setAttribute("admintoken", token); response.addCookie(new Cookie("admintoken", String.valueOf(token))); session.removeAttribute("csrftoken"); return new ModelAndView("redirect:adminintern.secu"); } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } catch (ClassCastException ccastEx) { ccastEx.printStackTrace(); } catch (NumberFormatException nfoEx) { nfoEx.printStackTrace(); } catch (DataAccessException e) { throw new SuperFatalAndReallyAnnoyingException( String.format("Sorry but %sis a bad grammar or has following problem %s", sql, e.getMessage())); } ModelAndView mv = returnToAdminLogin(session); return mv; }
From source file:eu.eidas.node.AbstractNodeServlet.java
/** * Sets HTTPOnly Header on the session to prevent cookies from being accessed through * client-side script./* ww w. j a v a2s. 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: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 w w.j ava 2 s. 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; } }
From source file:com.toft.widgets.login.LoginAction.java
/** * cookie??/*from w w w .j a v a2 s . c om*/ * * @throws Exception */ private void addCookie() throws Exception { String isChange = (String) this.getContext().getParam("isChange"); if (isChange == null) { return; } if (!isChange.equals("1")) { return; } String keepUser = (String) this.getContext().getParam("keepUser"); String keepPassword = (String) this.getContext().getParam("keepPassword"); if ("1".equals(keepUser)) { // cookie??? String[] keys = new String[] { "userId", "accountSet", "localeSet", "keepUser" }; for (int i = 0; i < keys.length; i++) { String value = (String) getContext().getParam(keys[i]); Cookie cookie = new Cookie(keys[i], value); cookie.setMaxAge(60 * 60 * 24 * 365); cookie.setPath("/"); getResponse().addCookie(cookie); } if ("1".equals(keepPassword)) { String[] passkeys = new String[] { "keepPassword", "password" }; for (int i = 0; i < passkeys.length; i++) { String value = (String) getContext().getParam(passkeys[i]); Cookie cookie = new Cookie(passkeys[i], value); cookie.setMaxAge(60 * 60 * 24 * 365); cookie.setPath("/"); getResponse().addCookie(cookie); } } else { String[] passkeys = new String[] { "keepPassword", "password" }; for (int i = 0; i < passkeys.length; i++) { Cookie cookie = new Cookie(passkeys[i], ""); cookie.setMaxAge(0); cookie.setPath("/"); getResponse().addCookie(cookie); } } } else { String[] keys = new String[] { "userId", "accountSet", "localeSet", "keepUser", "keepPassword", "password" }; for (int i = 0; i < keys.length; i++) { Cookie cookie = new Cookie(keys[i], ""); cookie.setMaxAge(0); cookie.setPath("/"); getResponse().addCookie(cookie); } } }
From source file:m.c.m.proxyma.resource.ProxymaResponseDataBeanTest.java
/** * Test of getCookie method, of class ProxymaResponseDataBean. *//*from w ww . j a v a2s. c om*/ public void testGetCookie() { System.out.println("getCookie"); ProxymaResponseDataBean instance = new ProxymaResponseDataBean(); instance.addCookie(new Cookie("name1", "value1")); instance.addCookie(new Cookie("name2", "value2")); instance.addCookie(new Cookie("name1", "value3")); Cookie result = instance.getCookie("name1"); assertEquals("value3", result.getValue()); result = instance.getCookie("name2"); assertEquals("value2", result.getValue()); //Test unexisting value result = instance.getCookie("unexistent"); assertNull(result); }
From source file:com.xwiki.authentication.trustedldap.TrustedLDAPAuthServiceImpl.java
public XWikiUser checkAuthSSO(String username, String password, XWikiContext context) throws XWikiException { Cookie cookie;/*www .j ava 2 s. c o m*/ LOG.debug("checkAuth"); LOG.debug("Action: " + context.getAction()); if (context.getAction().startsWith("logout")) { cookie = getCookie("XWIKISSOAUTHINFO", context); if (cookie != null) { cookie.setMaxAge(0); context.getResponse().addCookie(cookie); } return null; } Principal principal = null; if (LOG.isDebugEnabled()) { Cookie[] cookies = context.getRequest().getCookies(); if (cookies != null) { for (Cookie c : cookies) { LOG.debug("CookieList: " + c.getName() + " => " + c.getValue()); } } } cookie = getCookie("XWIKISSOAUTHINFO", context); if (cookie != null) { LOG.debug("Found Cookie"); String uname = decryptText(cookie.getValue(), context); if (uname != null) { principal = new SimplePrincipal(uname); } } XWikiUser user; // Authenticate if (principal == null) { principal = authenticate(username, password, context); if (principal == null) { return null; } LOG.debug("Saving auth cookie"); String encuname = encryptText(principal.getName().contains(":") ? principal.getName() : context.getDatabase() + ":" + principal.getName(), context); Cookie usernameCookie = new Cookie("XWIKISSOAUTHINFO", encuname); usernameCookie.setMaxAge(-1); usernameCookie.setPath("/"); context.getResponse().addCookie(usernameCookie); user = new XWikiUser(principal.getName()); } else { user = new XWikiUser(principal.getName().startsWith(context.getDatabase()) ? principal.getName().substring(context.getDatabase().length() + 1) : principal.getName()); } LOG.debug("XWikiUser=" + user); return user; }