Example usage for javax.servlet.http Cookie setMaxAge

List of usage examples for javax.servlet.http Cookie setMaxAge

Introduction

In this page you can find the example usage for javax.servlet.http Cookie setMaxAge.

Prototype

public void setMaxAge(int expiry) 

Source Link

Document

Sets the maximum age in seconds for this Cookie.

Usage

From source file:com.mawujun.util.web.CookieGenerator.java

/**
 * Remove the cookie that this generator describes from the response.
 * Will generate a cookie with empty value and max age 0.
 * <p>Delegates to <code>createCookie</code> for cookie creation.
 * @param response the HTTP response to remove the cookie from
 * @see #setCookieName/*from w w  w .ja  v  a  2  s. c  om*/
 * @see #setCookieDomain
 * @see #setCookiePath
 * @see #createCookie
 */
public void removeCookie(HttpServletResponse response) {
    Cookie cookie = createCookie("");
    cookie.setMaxAge(0);
    response.addCookie(cookie);
    if (logger.isDebugEnabled()) {
        logger.debug("Removed cookie with name [" + getCookieName() + "]");
    }
}

From source file:org.craftercms.security.authentication.impl.AuthenticationCookie.java

/**
 * Deletes the cookies from the context's response.
 *
 * @param context the context that holds the response to where an empty cookie is written (so the cookie is
 *                removed from the browser).
 *//*from ww  w. j  a va 2  s.c  o m*/
public void delete(RequestContext context) {
    String contextPath = context.getRequest().getContextPath();

    Cookie cookie = new Cookie(COOKIE, null);
    cookie.setPath(StringUtils.isNotEmpty(contextPath) ? contextPath : "/");
    cookie.setMaxAge(0);

    context.getResponse().addCookie(cookie);
}

From source file:com.openthinks.webscheduler.service.WebSecurityService.java

public Cookie createRememberMeCookie() {
    Cookie cookie = new Cookie(StaticDict.COOKIE_REMEMBER_ME, DigestUtils.sha1Hex(StaticUtils.UUID()));
    cookie.setMaxAge(StaticDict.COOKIE_REMEMBER_ME_EXPIRE_TIME);
    cookie.setPath(StaticUtils.getRootContext());
    return cookie;
}

From source file:org.slc.sli.dashboard.web.interceptor.SessionCheckInterceptor.java

/**
 * Prehandle performs a session check on all incoming requests to ensure a user with an active spring security session,
 *  is still authenticated against the api.
 *//*  w  w  w  .ja v a  2  s  .  c  om*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String token = SecurityUtil.getToken();

    JsonObject json = restClient.sessionCheck(token);

    // If the user is not authenticated, expire the cookie and set oauth_token to null
    if (!json.get(Constants.ATTR_AUTHENTICATED).getAsBoolean()) {
        SecurityContextHolder.getContext().setAuthentication(null);
        HttpSession session = request.getSession();
        session.setAttribute(SLIAuthenticationEntryPoint.OAUTH_TOKEN, null);
        for (Cookie c : request.getCookies()) {
            if (c.getName().equals(SLIAuthenticationEntryPoint.DASHBOARD_COOKIE)) {
                c.setMaxAge(0);
            }
        }

        // Only redirect if not error page
        if (!(request.getServletPath().equalsIgnoreCase(ErrorController.EXCEPTION_URL)
                || request.getServletPath().equalsIgnoreCase(ErrorController.TEST_EXCEPTION_URL))) {
            response.sendRedirect(request.getRequestURI());
            return false;
        }
    }

    return true;
}

From source file:org.sharetask.controller.UserController.java

@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public void performLogin(@RequestBody final UserPassword login, final HttpServletRequest request,
        final HttpServletResponse response) {
    final UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
            login.getUsername(), login.getPassword());
    try {/*from ww  w. j  a  va2 s.  c o  m*/
        final Authentication auth = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(auth);
        repository.saveContext(SecurityContextHolder.getContext(), request, response);
        rememberMeServices.loginSuccess(request, response, auth);
        // language cookie
        final UserInfoDTO user = userService.read(SecurityUtil.getCurrentSignedInUsername());
        final Cookie locale = new Cookie(RequestUltil.LOCALE, user.getLanguage());
        locale.setMaxAge(-1);
        locale.setPath("/");
        response.addCookie(locale);
        response.setStatus(HttpStatus.OK.value());
    } catch (final BadCredentialsException ex) {
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
    }
}

From source file:com.basicservice.controller.AdminController.java

private void prepareContext(Map map, HttpServletResponse response) {
    Map constants = service.getConstants();
    String csrf_token = "<secret changing key>"; // use SecureRandom to generate a random token
    Locale locale = LocaleContextHolder.getLocale();
    map.put("locale", locale.getLanguage());
    map.put("constants", constants);
    if (response != null) {
        map.put("csrf_token", csrf_token);
        Cookie cookie = new Cookie(Constants.CSRF_COOKIE_NAME, csrf_token);
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);//from w  ww  .  j  av  a  2s  . co m
    }
}

From source file:com.erudika.para.security.CachedCsrfTokenRepository.java

private void storeTokenAsCookie(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
    if (isValidButNotInCookie(token, request)) {
        Cookie c = new Cookie(cookieName, token.getToken());
        c.setMaxAge(Config.SESSION_TIMEOUT_SEC.intValue());
        // don't enable HttpOnly - javascript can't access the cookie if enabled
        c.setHttpOnly(false);//from   w ww  . j  av a  2 s.  c o m
        c.setPath("/");
        response.addCookie(c);
    }
}

From source file:com.persistent.cloudninja.web.security.CNAuthenticationProcessingFilter.java

private Cookie createCookie(User user, String currentCookie) {
    String newCookieValue = userDetailsService.createCookieValueFromUser(user);
    String cookieToUse = currentCookie;
    if (!currentCookie.equals(newCookieValue))
        cookieToUse = newCookieValue;// w  w  w .  ja  va  2s  . co m
    Cookie cookie = new Cookie(cookieName, cookieToUse);
    cookie.setMaxAge(-1);
    cookie.setPath("/");
    return cookie;
}

From source file:com.mobileman.projecth.web.util.PersistentCookieHelper.java

public void removeUser(HttpServletRequest request, HttpServletResponse response) {
    //remove from request
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (COOKIE_NAME.equals(c.getName())) {
                c.setValue("deleted");
                break;
            }//from www.ja v  a 2 s  .  c o  m
        }
    }

    //remove from browser
    Cookie cookie = new Cookie(COOKIE_NAME, "1");
    cookie.setPath(PATH);
    cookie.setMaxAge(0); //0 = remove cookie
    response.setContentType("text/html"); //else delete cookie not works
    response.addCookie(cookie);
}

From source file:net.geoprism.data.importer.ExcelController.java

@Override
public void exportExcelFile(String type, String country, String downloadToken)
        throws IOException, ServletException {

    try {//from   ww w  .  j  ava2s. co m
        // The reason we're including a cookie here is because the browser does not give us any indication of when our
        // response from the server is successful and its downloading the file.
        // This "hack" sends a downloadToken to the client, which the client then checks for the existence of every so
        // often. When the cookie exists, it knows its downloading it.
        // http://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download
        Cookie cookie = new Cookie("downloadToken", downloadToken);
        cookie.setMaxAge(10 * 60); // 10 minute cookie expiration
        resp.addCookie(cookie);

        InputStream istream = ExcelUtilDTO.exportExcelFile(this.getClientRequest(), type, country);

        try {
            // copy it to response's OutputStream
            this.resp.setContentType("application/xlsx");
            this.resp.setHeader("Content-Disposition", "attachment; filename=\"template.xlsx\"");

            IOUtils.copy(istream, this.resp.getOutputStream());

            this.resp.flushBuffer();
        } finally {
            istream.close();
        }
    } catch (RuntimeException e) {
        if (!resp.isCommitted()) {
            resp.reset();
        }

        ErrorUtility.prepareThrowable(e, req, resp, false, true);
    }
}