List of usage examples for javax.servlet.http Cookie setMaxAge
public void setMaxAge(int expiry)
From source file:au.org.paperminer.main.UserFilter.java
/** * Effectively logs out the user//from w w w . ja va 2s. c o m * @param resp */ private void removeCookie(HttpServletResponse resp) { Cookie cookie = new Cookie(PaperMinerConstants.PM_COOKIE, ""); cookie.setMaxAge(0); resp.addCookie(cookie); }
From source file:com.microsoft.azure.oidc.filter.helper.impl.SimpleAuthenticationHelper.java
private String addCookie(final HttpServletRequest httpRequest, final HttpServletResponse httpResponse, final String cookieName, final String cookieValue) { if (httpRequest == null || httpResponse == null || cookieName == null || cookieValue == null) { throw new PreconditionException("Required parameter is null"); }/* ww w .j av a2 s .com*/ final Cookie cookie = new Cookie(cookieName, ""); cookie.setValue(cookieValue); cookie.setMaxAge(-1); cookie.setSecure(true); cookie.setDomain(httpRequest.getServerName()); cookie.setPath("/"); cookie.setHttpOnly(true); httpResponse.addCookie(cookie); return cookie.getValue(); }
From source file:com.appeligo.search.actions.BaseAction.java
protected String getCookieId() { Cookie[] cookies = getServletRequest().getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals(BaseAction.COOKIE_ID)) { cookie.setMaxAge(Integer.MAX_VALUE); return cookie.getValue(); }//w w w. j a va 2s. com } } //No cookie found; String cookieValue = request.getRemoteAddr() + System.currentTimeMillis(); Cookie cookie = new Cookie(COOKIE_ID, cookieValue); cookie.setMaxAge(Integer.MAX_VALUE); response.addCookie(cookie); return cookieValue; }
From source file:controllers.UrlController.java
@RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies2 = request.getCookies(); user_detail = null;//w ww.j a v a 2 s . com if (cookies2 != null) { for (Cookie cookie : cookies2) { cookie.setValue(null); cookie.setMaxAge(0); response.addCookie(cookie); } } return "index"; }
From source file:com.stormcloud.ide.api.filter.UserFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { try {// www. j a v a 2 s . co m HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; LOG.info("Filter Request [" + request.getRemoteAddr() + "]"); MDC.put("api", httpRequest.getRequestURI()); if (httpRequest.getRequestURI().endsWith("/api/login")) { // configure MDC for the remainging trip MDC.put("userName", httpRequest.getRemoteUser()); LOG.debug("Login Request."); // it's a login request which succeeded (Basic Auth) // so we now need to genereate an authentication token // and store it in a cookie we sent back // create the cookie with key for consecutive Rest API Calls // Get user from db and add to the localthread User user = dao.getUser(httpRequest.getRemoteUser()); if (user == null) { LOG.error("User not found."); httpResponse.sendError(HttpStatus.FORBIDDEN.value()); httpResponse.flushBuffer(); return; } // update last login user.setLastLogin(Calendar.getInstance().getTime()); dao.save(user); RemoteUser.set(user); try { // set the key cookie Cookie keyCookie = new Cookie("stormcloud-key", createKey(user, httpRequest.getRemoteAddr())); keyCookie.setMaxAge(60 * 60 * 24); // 1 day keyCookie.setPath("/"); keyCookie.setSecure(true); httpResponse.addCookie(keyCookie); // set the username cookie Cookie userCookie = new Cookie("stormcloud-user", user.getUserName()); userCookie.setMaxAge(60 * 60 * 24); // 1 day userCookie.setPath("/"); userCookie.setSecure(true); httpResponse.addCookie(userCookie); } catch (NoSuchAlgorithmException e) { LOG.error(e); try { // no go httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value()); httpResponse.flushBuffer(); return; } catch (IOException ioe) { LOG.error(ioe); } } } else if (httpRequest.getRequestURI().endsWith("/api/user/createAccount")) { // intercept and do something with create account LOG.debug("Create Account Request."); } else { LOG.info("API Request."); // any other request than a login // we need to check the username and received key Cookie[] cookies = httpRequest.getCookies(); String userName = null; String key = null; if (cookies != null) { LOG.info("Found " + cookies.length + " Cookies"); // loop trough the cookies for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("stormcloud-user")) { LOG.debug("userName = " + cookies[i].getValue()); userName = cookies[i].getValue(); } if (cookies[i].getName().equals("stormcloud-key")) { LOG.debug("key = " + cookies[i].getValue()); key = cookies[i].getValue(); } } } if (userName == null || key == null) { LOG.info("Required credentials not found."); httpResponse.sendError(HttpStatus.FORBIDDEN.value()); httpResponse.flushBuffer(); return; } else { // configure MDC for the remainging trip MDC.put("userName", userName); // get user LOG.debug("Get Persisted User"); User user = dao.getUser(userName); if (user == null) { httpResponse.sendError(HttpStatus.FORBIDDEN.value()); httpResponse.flushBuffer(); return; } RemoteUser.set(user); try { String matchKey = createKey(user, httpRequest.getRemoteAddr()); LOG.info("Validating Key."); if (!matchKey.equals(key)) { LOG.warn("Invalid Key!"); httpResponse.sendError(HttpStatus.FORBIDDEN.value()); httpResponse.flushBuffer(); return; } else { LOG.info("Request Authenticated"); } } catch (NoSuchAlgorithmException e) { LOG.error(e); try { // no go httpResponse.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value()); httpResponse.flushBuffer(); return; } catch (IOException ioe) { LOG.error(ioe); } } } } chain.doFilter(request, response); } catch (IOException e) { LOG.error(e); } catch (ServletException e) { LOG.error(e); } finally { // clear the logging diagnostics context MDC.clear(); // Remove the user from memoty RemoteUser.destroy(); } }
From source file:net.anthonychaves.bookmarks.web.PersistentLoginFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; Cookie tokenCookie = getCookieByName(httpRequest.getCookies(), "loginToken"); HttpSession session = httpRequest.getSession(); User user = (User) session.getAttribute("user"); if (user == null && tokenCookie != null) { user = tokenService.loginWithToken(tokenCookie.getValue()); String tokenValue = tokenService.setupNewLoginToken(user); httpRequest.getSession().setAttribute("user", user); tokenCookie.setMaxAge(0); httpResponse.addCookie(tokenCookie); tokenCookie = new Cookie("loginToken", tokenValue); tokenCookie.setPath("/bookmarks"); tokenCookie.setMaxAge(168 * 60 * 60); httpResponse.addCookie(tokenCookie); }// ww w .j a va2 s . c o m chain.doFilter(httpRequest, httpResponse); }
From source file:com.taobao.ad.easyschedule.exsession.request.session.SessionCookieStore.java
/** * @param response/*from w ww .j ava 2 s. com*/ * @param config * @param value * * @throws Exception */ private void removeCookie(HttpServletResponse response, SessionAttributeConfig config) throws Exception { String cookieName = config.getNickName(); Cookie cookie = new Cookie(cookieName, null); ; // COOKIE String cookiePath = COOKIE_PATH; if (config.getCookiePath() != null) { cookiePath = config.getCookiePath(); } cookie.setPath(cookiePath); log.debug("remove cookie name: " + cookieName); cookie.setMaxAge(0); String domain = config.getDomain(); if ((domain != null) && (domain.length() > 0)) { cookie.setDomain(domain); } response.addCookie(cookie); }
From source file:com.agiletec.plugins.jpcontentfeedback.aps.internalservlet.feedback.ContentFeedbackAction.java
protected void addCookieRating(String contentId) { UserDetails currentUser = this.getCurrentUser(); String cookieName = CheckVotingUtil.getCookieName(currentUser.getUsername(), contentId); String cookieValue = CheckVotingUtil.getCookieValue(currentUser.getUsername(), contentId); Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setMaxAge(365 * 24 * 60 * 60);//one year this.getResponse().addCookie(cookie); }
From source file:com.agiletec.plugins.jpcontentfeedback.aps.internalservlet.feedback.ContentFeedbackAction.java
protected void addCookieRating(int commentId) { UserDetails currentUser = this.getCurrentUser(); String cookieName = CheckVotingUtil.getCookieName(currentUser.getUsername(), commentId); String cookieValue = CheckVotingUtil.getCookieValue(currentUser.getUsername(), commentId); Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setMaxAge(365 * 24 * 60 * 60);//one year this.getResponse().addCookie(cookie); }
From source file:course.BlogController.java
private void initializeRoutes() throws IOException { // this is the blog home page get(new FreemarkerBasedRoute("/", "blog_template.ftl") { @Override/* ww w .j av a2 s .c o m*/ public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); // this is where we would normally load up the blog data // but this week, we just display a placeholder. HashMap<String, String> root = new HashMap<String, String>(); template.process(root, writer); } }); // handle the signup post post(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String email = request.queryParams("email"); String username = request.queryParams("username"); String password = request.queryParams("password"); String verify = request.queryParams("verify"); HashMap<String, String> root = new HashMap<String, String>(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("email", StringEscapeUtils.escapeHtml4(email)); if (validateSignup(username, password, verify, email, root)) { // good user System.out.println("Signup: Creating user with: " + username + " " + password); if (!userDAO.addUser(username, password, email)) { // duplicate user root.put("username_error", "Username already in use, Please choose another"); template.process(root, writer); } else { // good user, let's start a session String sessionID = sessionDAO.startSession(username); System.out.println("Session ID is" + sessionID); response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/welcome"); } } else { // bad signup System.out.println("User Registration did not validate"); template.process(root, writer); } } }); // present signup form for blog get(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); // initialize values for the form. root.put("username", ""); root.put("password", ""); root.put("email", ""); root.put("password_error", ""); root.put("username_error", ""); root.put("email_error", ""); root.put("verify_error", ""); template.process(root, writer); } }); get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("welcome() can't identify the user, redirecting to signup"); response.redirect("/signup"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // present the login page get(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("username", ""); root.put("login_error", ""); template.process(root, writer); } }); // process output coming from login form. On success redirect folks to // the welcome page // on failure, just return an error and let them try again. post(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = request.queryParams("username"); String password = request.queryParams("password"); System.out.println("Login: User submitted: " + username + " " + password); Document user = userDAO.validateLogin(username, password); if (user != null) { // valid user, let's log them in String sessionID = sessionDAO.startSession(user.get("_id").toString()); if (sessionID == null) { response.redirect("/internal_error"); } else { // set the cookie for the user's browser response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/welcome"); } } else { SimpleHash root = new SimpleHash(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("password", ""); root.put("login_error", "Invalid Login"); template.process(root, writer); } } }); // allows the user to logout of the blog get(new FreemarkerBasedRoute("/logout", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String sessionID = getSessionCookie(request); if (sessionID == null) { // no session to end response.redirect("/login"); } else { // deletes from session table sessionDAO.endSession(sessionID); // this should delete the cookie Cookie c = getSessionCookieActual(request); c.setMaxAge(0); response.raw().addCookie(c); response.redirect("/login"); } } }); // used to process internal errors get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("error", "System has encountered an error."); template.process(root, writer); } }); }