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.google.youtube.captions.AuthSubLogout.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String username = Util.getCookie(req, Util.CURRENT_USERNAME);

    if (!Util.isEmptyOrNull(username)) {
        try {//w ww  .  j ava 2 s.c  o m
            String authSubCookie = Util.getCookie(req, Util.AUTH_SUB_COOKIE);
            JSONObject cookieAsJSON = new JSONObject(authSubCookie);

            if (cookieAsJSON.has(username)) {
                String authSubToken = cookieAsJSON.getString(username);

                AuthSubUtil.revokeToken(authSubToken, null);

                cookieAsJSON.remove(username);

                Cookie cookie = new Cookie(Util.AUTH_SUB_COOKIE, cookieAsJSON.toString());
                cookie.setMaxAge(Util.COOKIE_LIFETIME);
                resp.addCookie(cookie);

                cookie = new Cookie(Util.CURRENT_AUTHSUB_TOKEN, "");
                cookie.setMaxAge(Util.COOKIE_LIFETIME);
                resp.addCookie(cookie);

                cookie = new Cookie(Util.CURRENT_USERNAME, "");
                cookie.setMaxAge(Util.COOKIE_LIFETIME);
                resp.addCookie(cookie);
            }
        } catch (AuthenticationException e) {
            LOG.log(Level.WARNING, "", e);
        } catch (GeneralSecurityException e) {
            LOG.log(Level.WARNING, "", e);
        } catch (JSONException e) {
            LOG.log(Level.WARNING, "", e);
        }
    }

    resp.sendRedirect("/");
}

From source file:net.prasenjit.auth.config.CustomAjaxAwareHandler.java

/** {@inheritDoc} */
@Override//from w w  w . j av a 2  s  . co  m
public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    request.setAttribute("javax.servlet.error.status_code", HttpServletResponse.SC_FORBIDDEN);
    request.setAttribute("org.springframework.boot.autoconfigure.web.DefaultErrorAttributes.ERROR",
            accessDeniedException);
    if (accessDeniedException instanceof CsrfException && !response.isCommitted()) {
        // Remove the session cookie so that client knows it's time to obtain a new CSRF token
        String pCookieName = "CSRF-TOKEN";
        Cookie cookie = new Cookie(pCookieName, "");
        cookie.setMaxAge(0);
        cookie.setHttpOnly(false);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    delegatedAccessDeniedHandler.handle(request, response, accessDeniedException);
}

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

/**
 * Saves the cookie in the context's response.
 *
 * @param context      the context that holds the response to where the cookie is written.
 * @param cookieMaxAge the max age of the cookie.
 *///from  www.  j a  va2s . com
public void save(RequestContext context, int cookieMaxAge) {
    Cookie cookie = new Cookie(COOKIE, toCookieValue());
    cookie.setPath("/");
    cookie.setMaxAge(cookieMaxAge);
    context.getResponse().addCookie(cookie);
}

From source file:au.gov.dto.dibp.appointments.security.csrf.CookieBasedCsrfTokenRepository.java

@Override
public void saveToken(CsrfToken token, HttpServletRequest request, HttpServletResponse response) {
    Cookie csrfCookie;
    if (token == null) {
        csrfCookie = new Cookie(CSRF_COOKIE_AND_PARAMETER_NAME, "");
        csrfCookie.setMaxAge(0);
    } else {//ww w  .j a va  2 s  .c  om
        csrfCookie = new Cookie(token.getParameterName(), token.getToken());
        csrfCookie.setMaxAge(COOKIE_MAX_AGE_SECONDS);
    }
    csrfCookie.setHttpOnly(true);
    csrfCookie.setSecure(request.isSecure());
    response.addCookie(csrfCookie);
}

From source file:fi.helsinki.opintoni.security.CustomAuthenticationSuccessHandler.java

private void addHasLoggedInCookie(HttpServletResponse response) {
    Cookie cookie = new Cookie(Constants.OPINTONI_HAS_LOGGED_IN, Boolean.TRUE.toString());
    cookie.setMaxAge(Integer.MAX_VALUE);
    addCookie(response, cookie);//from   w w w  . j  ava 2  s  .co  m
}

From source file:org.mascherl.session.MascherlSessionStorage.java

public void saveSession(MascherlSession session, HttpServletResponse response) {
    if (!session.wasModified()) {
        return; // no need to update an unmodified session
    }//from www. j a  v a2  s  . c  o m

    String data = session.serialize();
    if (data.length() > MAX_DATA_SIZE) {
        throw new IllegalStateException("Session data exceeds limit");
    }

    String encryptedValue = cryptoHelper.encryptAES(data);

    Cookie cookie = new Cookie(cookieName, encryptedValue);
    cookie.setMaxAge(EXPIRE_ON_BROWSER_CLOSE);
    response.addCookie(cookie);
}

From source file:com.parleys.server.frontend.web.ipad.filters.LoginFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse response, final FilterChain chain)
        throws IOException {
    final HttpServletResponse res = (HttpServletResponse) response;
    final PrintWriter writer = res.getWriter();
    res.setStatus(HttpServletResponse.SC_OK);
    res.setHeader("Cache-Control", "must-revalidate");
    res.setHeader("Expires", "Fri, 30 Oct 1998 14:19:41 GMT");
    try {//from   w w w.java2 s. c  om
        final String username = req.getParameter("username");
        final String password = req.getParameter("password");
        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            final ParleysService bean = applicationContext.getBean(ParleysService.class);
            final Long userId = bean.getUserId(username, password);

            final String usernameAndPassword = username + ";" + password;
            final String encrypted = AESEncrypter.INSTANCE.encrypt(usernameAndPassword);
            final Cookie rememberMeCookie = new Cookie(PARLEYS_REMEMBER_ME_IPAD, encrypted);
            rememberMeCookie.setMaxAge(3600 * 24 * 7 * 26); // A half year
            res.addCookie(rememberMeCookie);

            writeUserId(writer, userId);
        } else {
            writeError(writer);
        }
    } catch (Exception e) {
        writeError(writer);
    }
}

From source file:org.sharetask.security.StoreUserInformationAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    if (authentication instanceof ClientAuthenticationToken) {
        log.debug("Token is pac4j token.");

        String language = Language.EN.getCode();
        UsernamePasswordAuthenticationToken authentToken;
        final CommonProfile profile = (CommonProfile) ((ClientAuthenticationToken) authentication)
                .getUserProfile();//from   w w w  .j ava2s.c o  m
        if (userRepository.findByUsername(profile.getEmail()) == null) {
            log.debug("User with name: {} doesne exist's. Will be created", profile.getEmail());
            final UserInformation userInformation = new UserInformation(profile.getEmail());
            userInformation.setName(profile.getFirstName());
            userInformation.setSurName(profile.getFamilyName());
            userInformation.setLanguage(language);
            final ArrayList<Role> list = new ArrayList<Role>();
            list.add(Role.ROLE_USER);
            userInformation.setRoles(list);
            userRepository.save(userInformation);
            final List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            authorities.add(new SimpleGrantedAuthority(Role.ROLE_USER.name()));
            authentToken = new UsernamePasswordAuthenticationToken(profile.getEmail(), "", authorities);
        } else {
            final UserInformation user = userRepository.read(profile.getEmail());
            language = user.getLanguage();
            final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            authentToken = new UsernamePasswordAuthenticationToken(profile.getEmail(), "", authorities);
        }
        // language cookie
        final Cookie locale = new Cookie(RequestUltil.LOCALE, language);
        locale.setMaxAge(-1);
        locale.setPath("/");
        response.addCookie(locale);

        SecurityContextHolder.getContext().setAuthentication(authentToken);
    }

    super.onAuthenticationSuccess(request, response, authentication);
}

From source file:com.adobe.acs.commons.forms.helpers.impl.PostRedirectGetWithCookiesFormHelperImpl.java

/**
 * Adds a cookie containing the serialised contents of the form to a cookie named after the GET lookup key
 * @param response//from  w  ww  .jav a2s. c o  m
 * @param form
 * @throws JSONException
 */
protected void addFlashCookie(SlingHttpServletResponse response, Form form) throws JSONException {
    final String name = this.getGetLookupKey(form.getName());
    final String value = getQueryParameterValue(form);
    final Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(COOKIE_MAX_AGE);
    CookieUtil.addCookie(cookie, response);
}

From source file:controllers.Parent_Controller.java

public Cookie set_Cookie(String name, String value, int ttl) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(ttl * 60 * 60);
    return cookie;
    //response.addCookie(cookie); 
}