List of usage examples for javax.servlet.http Cookie setPath
public void setPath(String uri)
From source file:com.erudika.para.utils.Utils.java
/** * Sets a cookie./*from ww w .j ava 2 s . c o m*/ * @param name the name * @param value the value * @param req HTTP request * @param res HTTP response * @param httpOnly HTTP only flag * @param maxAge max age */ public static void setRawCookie(String name, String value, HttpServletRequest req, HttpServletResponse res, boolean httpOnly, int maxAge) { if (StringUtils.isBlank(name) || StringUtils.isBlank(value) || req == null || res == null) { return; } Cookie cookie = new Cookie(name, value); cookie.setHttpOnly(httpOnly); cookie.setMaxAge(maxAge < 0 ? Config.SESSION_TIMEOUT_SEC.intValue() : maxAge); cookie.setPath("/"); cookie.setSecure(req.isSecure()); res.addCookie(cookie); }
From source file:io.cfp.auth.service.CookieService.java
public Cookie getTokenCookie(String tokenValue) { Cookie tokenCookie = new Cookie("token", tokenValue); tokenCookie.setPath("/"); tokenCookie.setHttpOnly(true); // secure Token to be invisible from // javascript in the browser tokenCookie.setDomain(cookieDomain); tokenCookie.setMaxAge((int) Duration.ofHours(TokenService.TOKEN_EXPIRATION).getSeconds()); return tokenCookie; }
From source file:com.liferay.portal.action.LoginAction.java
public static void login(HttpServletRequest req, HttpServletResponse res, String login, String password, boolean rememberMe) throws Exception { CookieKeys.validateSupportCookie(req); HttpSession ses = req.getSession();/* www. j a v a2 s . c o m*/ long userId = GetterUtil.getLong(login); int authResult = Authenticator.FAILURE; Company company = PortalUtil.getCompany(req); // boolean ldaplogin = false; if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) { LdapContext ctx = PortalLDAPUtil.getContext(company.getCompanyId()); String accountname = ""; try { User user1 = UserLocalServiceUtil.getUserByScreenName(company.getCompanyId(), login); Properties env = new Properties(); String baseProviderURL = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_BASE_PROVIDER_URL); String userDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_USERS_DN); String baseDN = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_BASE_DN); String filter = PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_SEARCH_FILTER); filter = StringUtil.replace(filter, new String[] { "@company_id@", "@email_address@", "@screen_name@", "@user_id@" }, new String[] { String.valueOf(company.getCompanyId()), "", login, login }); try { SearchControls cons = new SearchControls(SearchControls.SUBTREE_SCOPE, 1, 0, null, false, false); NamingEnumeration enu = ctx.search(userDN, filter, cons); if (enu.hasMoreElements()) { SearchResult result = (SearchResult) enu.nextElement(); accountname = result.getName(); } } catch (Exception e1) { e1.printStackTrace(); } env.put(Context.INITIAL_CONTEXT_FACTORY, PrefsPropsUtil.getString(PropsUtil.LDAP_FACTORY_INITIAL)); env.put(Context.PROVIDER_URL, LDAPUtil.getFullProviderURL(baseProviderURL, baseDN)); env.put(Context.SECURITY_PRINCIPAL, accountname + "," + userDN); env.put(Context.SECURITY_CREDENTIALS, password); new InitialLdapContext(env, null); ldaplogin = true; System.out.println("LDAP Login"); } catch (Exception e) { SessionErrors.add(req, "ldapAuthentication"); e.printStackTrace(); System.out.println("LDAP error login"); return; } } // Map headerMap = new HashMap(); Enumeration enu1 = req.getHeaderNames(); while (enu1.hasMoreElements()) { String name = (String) enu1.nextElement(); Enumeration enu2 = req.getHeaders(name); List headers = new ArrayList(); while (enu2.hasMoreElements()) { String value = (String) enu2.nextElement(); headers.add(value); } headerMap.put(name, (String[]) headers.toArray(new String[0])); } Map parameterMap = req.getParameterMap(); if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_EA)) { authResult = UserLocalServiceUtil.authenticateByEmailAddress(company.getCompanyId(), login, password, headerMap, parameterMap); userId = UserLocalServiceUtil.getUserIdByEmailAddress(company.getCompanyId(), login); } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_SN)) { authResult = UserLocalServiceUtil.authenticateByScreenName(company.getCompanyId(), login, password, headerMap, parameterMap); userId = UserLocalServiceUtil.getUserIdByScreenName(company.getCompanyId(), login); } else if (company.getAuthType().equals(CompanyImpl.AUTH_TYPE_ID)) { authResult = UserLocalServiceUtil.authenticateByUserId(company.getCompanyId(), userId, password, headerMap, parameterMap); } boolean OTPAuth = false; if (GetterUtil.getBoolean(PropsUtil.get("use.yubicoauthentication"), false) == true) { String otppasswd = ParamUtil.getString(req, "otp"); String userslist = GetterUtil.getString(PropsUtil.get("yubico.users.not.require.otp"), "root"); if (userslist.contains(login)) { authResult = Authenticator.SUCCESS; } else { OTPAuth = SecurityUtils.verifyOTP(otppasswd, login); if (authResult == Authenticator.SUCCESS && OTPAuth) { authResult = Authenticator.SUCCESS; } else { authResult = Authenticator.FAILURE; } } } if (PrefsPropsUtil.getString(company.getCompanyId(), PropsUtil.LDAP_AUTH_ENABLED).equals("true")) { if (!login.equals("root")) { if (ldaplogin) { authResult = Authenticator.SUCCESS; } } } if (authResult == Authenticator.SUCCESS) { boolean loginViaPortal = true; setLoginCookies(req, res, ses, userId, rememberMe); // login to epsos String language = GeneralUtils.getLocale(req); SpiritEhrWsClientInterface webService = EpsosHelperService.getInstance().getWebService(req); InitUserObj initUserObj = EpsosHelperImpl.createEpsosUserInformation(req, res, language, webService, userId, company.getCompanyId(), login, loginViaPortal); SpiritUserClientDto usr = initUserObj.getUsr(); Assertion assertion = initUserObj.getAssertion(); if (Validator.isNotNull(usr)) { req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTIONID, assertion.getID()); req.getSession().setAttribute(EpsosHelperService.EPSOS_LOGIN_INFORMATION_ASSERTION, assertion); req.getSession().setAttribute(EPSOS_LOGIN_INFORMATION_ATTRIBUTE, usr); } else { SessionErrors.add(req, "User doesn't belong to epSOS role so you can't login"); } if (Validator.isNull(usr) && (!(login.equals("root")))) { try { Cookie cookie = new Cookie(CookieKeys.ID, StringPool.BLANK); cookie.setMaxAge(0); cookie.setPath("/"); CookieKeys.addCookie(res, cookie); cookie = new Cookie(CookieKeys.PASSWORD, StringPool.BLANK); cookie.setMaxAge(0); cookie.setPath("/"); CookieKeys.addCookie(res, cookie); try { ses.invalidate(); } catch (Exception e) { } } catch (Exception e) { req.setAttribute(PageContext.EXCEPTION, e); } throw new AuthException(); } } else { throw new AuthException(); } }
From source file:het.springapp.security.CsrfTokenGeneratorFilter.java
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //Create CSRF Token from request param CsrfToken token = (CsrfToken) request.getAttribute("_csrf"); //Set up CSRF Response Headers for: HEADER, TOKEN & PARAM //response.setHeader("X-CSRF-HEADER", token.getHeaderName()); //response.setHeader("X-CSRF-PARAM", token.getParameterName()); // response.setHeader("X-CSRF-TOKEN", token.getToken()); Cookie cookie = new Cookie("X-CSRF-TOKEN", token.getToken()); cookie.setPath("/"); response.addCookie(cookie);//www. j a va 2 s . c om //Filter filterChain.doFilter(request, response); }
From source file:com.liferay.portal.action.LoginAction.java
public static void setLoginCookies(HttpServletRequest req, HttpServletResponse res, HttpSession ses, long userId, boolean rememberMe) throws PortalException, SystemException, EncryptorException { if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SESSION_ENABLE_PHISHING_PROTECTION))) { // Invalidate the previous session to prevent phishing LastPath lastPath = (LastPath) ses.getAttribute(WebKeys.LAST_PATH); // GNOMON Gi9: KEEP ANY USER_CARRY ATTRIBUTES (for example shopping cart) HashMap userCarryAttributes = getUserCarryAttributes(ses); try {//from w w w . ja v a 2 s . c o m ses.invalidate(); } catch (Exception e) { _log.info("Session has already invalidated"); } ses = req.getSession(true); addSessionAttributes(ses, userCarryAttributes); if (lastPath != null) { ses.setAttribute(WebKeys.LAST_PATH, lastPath); } } // Set cookies String domain = PropsUtil.get(PropsUtil.SESSION_COOKIE_DOMAIN); User user = UserLocalServiceUtil.getUserById(userId); Company company = CompanyLocalServiceUtil.getCompanyById(user.getCompanyId()); String userIdString = String.valueOf(userId); ses.setAttribute("j_username", userIdString); ses.setAttribute("j_password", user.getPassword()); ses.setAttribute("j_remoteuser", userIdString); ses.setAttribute(WebKeys.USER_PASSWORD, user.getPassword()); Cookie idCookie = new Cookie(CookieKeys.ID, UserLocalServiceUtil.encryptUserId(userIdString)); if (Validator.isNotNull(domain)) { idCookie.setDomain(domain); } idCookie.setPath(StringPool.SLASH); Cookie passwordCookie = new Cookie(CookieKeys.PASSWORD, Encryptor.encrypt(company.getKeyObj(), user.getPassword())); if (Validator.isNotNull(domain)) { passwordCookie.setDomain(domain); } passwordCookie.setPath(StringPool.SLASH); int loginMaxAge = GetterUtil.getInteger(PropsUtil.get(PropsUtil.COMPANY_SECURITY_AUTO_LOGIN_MAX_AGE), CookieKeys.MAX_AGE); if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SESSION_DISABLED))) { rememberMe = true; } if (rememberMe) { idCookie.setMaxAge(loginMaxAge); passwordCookie.setMaxAge(loginMaxAge); } else { idCookie.setMaxAge(0); passwordCookie.setMaxAge(0); } Cookie loginCookie = new Cookie(CookieKeys.LOGIN, user.getLogin()); if (Validator.isNotNull(domain)) { loginCookie.setDomain(domain); } loginCookie.setPath(StringPool.SLASH); loginCookie.setMaxAge(loginMaxAge); Cookie screenNameCookie = new Cookie(CookieKeys.SCREEN_NAME, Encryptor.encrypt(company.getKeyObj(), user.getScreenName())); if (Validator.isNotNull(domain)) { screenNameCookie.setDomain(domain); } screenNameCookie.setPath(StringPool.SLASH); screenNameCookie.setMaxAge(loginMaxAge); CookieKeys.addCookie(res, idCookie); CookieKeys.addCookie(res, passwordCookie); CookieKeys.addCookie(res, loginCookie); CookieKeys.addCookie(res, screenNameCookie); //add entry to user tracking if needed boolean trackUser = GetterUtil.getBoolean(PropsUtil.get(user.getCompanyId(), "gn.user.tracking.enabled"), false); if (trackUser) { GnUserTracking track = new GnUserTracking(); track.setCompanyId(user.getCompanyId()); track.setUserId(user.getUserId()); track.setLoginDate(new Date()); String fromIp = req.getHeader("X-Forwarded-For"); if (Validator.isNull(fromIp)) fromIp = req.getRemoteAddr() + (Validator.isNotNull(req.getRemoteHost()) && !req.getRemoteAddr().equals(req.getRemoteHost()) ? "( " + req.getRemoteHost() + " )" : ""); track.setFromIp(fromIp); GnPersistenceService.getInstance(null).createObject(track); } EventsService.getInstance().createEvent(user, "PortalAuth", "User " + user.getScreenName() + " has logged in " + req.getServerName(), "loginaction", null); }
From source file:org.nuxeo.ecm.webapp.action.ThemeEditorAction.java
private Cookie createCookie(String name, String value) { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); // expires when the browser is closed cookie.setMaxAge(-1);/*from ww w.ja va 2 s . c o m*/ return cookie; }
From source file:csns.web.controller.IndexController.java
@RequestMapping({ "/department/{dept}/", "/department/{dept}" }) public String index(@PathVariable String dept, ModelMap models, HttpServletResponse response) { Department department = departmentDao.getDepartment(dept); if (department == null) return "redirect:/"; Cookie cookie = new Cookie("default-dept", dept); cookie.setPath("/"); cookie.setMaxAge(100000000);//from w ww . ja v a2s.com response.addCookie(cookie); models.addAttribute("department", department); models.addAttribute("newses", newsDao.getNews(department)); return "department/index"; }
From source file:de.sainth.recipe.backend.rest.controller.LogoutController.java
@RequestMapping() @ResponseStatus(HttpStatus.NO_CONTENT)/*from www . j a v a 2 s .c o m*/ void logout(HttpServletRequest request, HttpServletResponse response) { if ("/logout".equals(request.getServletPath())) { Optional<Cookie> cookie = Arrays.stream(request.getCookies()) .filter(c -> "recipe_bearer".equals(c.getName())).findFirst(); if (cookie.isPresent()) { Cookie c = cookie.get(); c.setValue(""); c.setPath("/"); c.setMaxAge(0); response.addCookie(c); } response.setStatus(HttpServletResponse.SC_NO_CONTENT); } }
From source file:com.woonoz.proxy.servlet.CookieFormatterTest.java
@Test public void testCookieNoValue() throws InvalidCookieException { Cookie cookie = new Cookie("JSESSIONID", ""); cookie.setPath("/"); CookieFormatter formatter = CookieFormatter.createFromServletCookie(cookie); Assert.assertEquals("JSESSIONID=; path=/;", formatter.asString()); }
From source file:com.woonoz.proxy.servlet.CookieFormatterTest.java
@Test(expected = InvalidCookieException.class) public void testCookieNullValue() throws InvalidCookieException { Cookie cookie = new Cookie("JSESSIONID", null); cookie.setPath("/"); CookieFormatter.createFromServletCookie(cookie); }