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:fi.hoski.web.auth.LoginServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    response.setHeader("Cache-Control", "private, max-age=0, no-cache");
    String action = request.getParameter("action");
    try {/*from   w w  w  .  j a  v  a2s.co m*/
        if (action == null || action.equals("login")) {
            // login

            String email = request.getParameter("email");
            String password = request.getParameter("password");
            email = (email != null) ? email.trim() : null;

            // 1. check params
            if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
                log("email or password not ok");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                // 2. check user exists
                Map<String, Object> user = userDirectory.authenticateUser(email, password);
                if (user == null) {
                    log("user not found");
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    // 3. create session
                    HttpSession session = request.getSession(true);
                    session.setAttribute(USER, user);

                    response.getWriter().println("Logged in");
                }
            }
        } else {
            // logout

            HttpSession session = request.getSession(false);
            if (session != null) {
                session.setAttribute(USER, null);
                session.invalidate();
            }

            // change Cookie so that Vary: Cookie works
            Cookie c = new Cookie("JSESSIONID", null);
            c.setMaxAge(0);
            response.addCookie(c);

            response.getWriter().println("Logged out");
        }
    } catch (UnavailableException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    } catch (EmailNotUniqueException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    }
}

From source file:com.glaf.core.util.RequestUtils.java

public static void removeLoginUser(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            if (StringUtils.equals(cookie.getName(), Constants.COOKIE_NAME)) {
                cookie.setMaxAge(0);
                cookie.setPath("/");
                cookie.setValue(UUID32.getUUID());
                response.addCookie(cookie);
                logger.debug("remove user from cookie");
            }// w  w  w .  j  a  v a 2 s  .  com
        }
    }

    HttpSession session = request.getSession(false);
    if (session != null) {
        session.removeAttribute(Constants.LOGIN_INFO);
        session.invalidate();
    }
}

From source file:com.tenduke.example.scribeoauth.SessionManager.java

/**
 * Terminates session./*from  ww w  .  j  a v  a 2  s  . co m*/
 * @param request Client HTTP request.
 * @param response HTTP response.
 */
public void endSession(final HttpServletRequest request, final HttpServletResponse response) {
    //
    final Cookie cookie = new Cookie(SIGNED_SESSION_COOKIE_NAME, null);
    cookie.setMaxAge(0);
    cookie.setPath("/");
    response.addCookie(cookie);
}

From source file:com.googlesource.gerrit.plugins.github.oauth.GitHubLogin.java

private String getScopesKey(HttpServletRequest request, HttpServletResponse response) {
    String scopeRequested = request.getParameter("scope");
    if (scopeRequested == null) {
        scopeRequested = getScopesKeyFromCookie(request);
    }//  w  w w .  j  a v a 2 s.c  o  m

    if (scopeRequested != null) {
        Cookie scopeCookie = new Cookie("scope", scopeRequested);
        scopeCookie.setPath("/");
        scopeCookie.setMaxAge((int) SCOPE_COOKIE_NEVER_EXPIRES);
        response.addCookie(scopeCookie);
    }

    return Objects.firstNonNull(scopeRequested, "scopes");
}

From source file:com.atlassian.jira.security.xsrf.SimpleXsrfTokenGenerator.java

private void addNewCookie(HttpServletRequest httpServletRequest, String token,
        HttpServletResponse httpServletResponse) {
    final Cookie cookie = new Cookie(TOKEN_HTTP_SESSION_KEY, token);
    cookie.setPath(getRequestContext(httpServletRequest));
    cookie.setMaxAge(-1); // expire with the browser exit
    cookie.setSecure(httpServletRequest.isSecure());
    httpServletResponse.addCookie(cookie);
    httpServletRequest.setAttribute(SET_COOKIE_PENDING, token);
}

From source file:com.alfaariss.oa.util.web.CookieTool.java

/**
 * Remove cookie./*from   w ww.j  a  v a2  s  .c  om*/
 * @param sCookie The cookie name.
 * @param oRequest The servlet request.
 * @param oResponse The servlet response.
 */
public void removeCookie(String sCookie, HttpServletRequest oRequest, HttpServletResponse oResponse) {
    Cookie cookie = createCookie(sCookie, "jimmorrisonisstillalive", oRequest);
    cookie.setMaxAge(0); //Expire                        
    oResponse.addCookie(cookie);
}

From source file:com.companyname.services.PlatCookieService.java

public void invalidateCookie(HttpServletRequest request, HttpServletResponse response, String _cookieName) {
    logger.info("cancelling cookie named: " + _cookieName);

    // if cookie does not exist, do nothing
    Cookie cookie = getCookie(request, _cookieName);

    if (cookie == null) {
        return;//from w w  w  .j a  v a 2 s.  co m
    }

    cookie = new Cookie(_cookieName, null);
    cookie.setValue("");
    cookie.setMaxAge(0);
    cookie.setPath(getCookiePath());
    cookie.setDomain(getCookieDomain());
    response.addCookie(cookie);
}

From source file:com.qut.middleware.spep.authn.bindings.impl.AuthnPostBindingImpl.java

private void handleAuthnRequest(HttpServletRequest request, HttpServletResponse response,
        AuthnProcessorData data, SPEP spep) throws AuthenticationException {
    try {//w w w .  j av a  2s . c om
        String remoteAddress = request.getRemoteAddr();

        this.logger.info("[Authn for {}] Initiating HTTP POST binding. Creating AuthnRequest", remoteAddress);
        String document = buildAuthnRequestDocument(request.getParameter("redirectURL"), request, response,
                data, spep);
        PrintStream out = new PrintStream(response.getOutputStream());

        /* Set cookie to allow javascript enabled browsers to autosubmit, ensures navigation with the back button is not broken because auto submit is active for only a very short period */
        Cookie autoSubmit = new Cookie("spepAutoSubmit", "enabled");
        autoSubmit.setMaxAge(172800); //set expiry to be 48 hours just to make sure we still work with badly configured clocks skewed from GMT
        autoSubmit.setPath("/");
        response.addCookie(autoSubmit);

        response.setStatus(HttpServletResponse.SC_OK);
        response.setHeader("Content-Type", "text/html");

        out.print(document);

        out.close();

        this.logger.info("[Authn for {}] Sent AuthnRequest successfully", remoteAddress);
    } catch (IOException e) {
        throw new AuthenticationException("Unable to send response due to an I/O error.", e);
    }
}

From source file:fr.univlille2.ecm.platform.ui.web.auth.cas2.SecurityExceptionHandler.java

@Override
public void handleException(HttpServletRequest request, HttpServletResponse response, Throwable t)
        throws IOException, ServletException {

    @SuppressWarnings("deprecation")
    Throwable unwrappedException = unwrapException(t);
    log.debug("handleException#in");
    if (!ExceptionHelper.isSecurityError(unwrappedException)
            && !response.containsHeader(SSO_INITIAL_URL_REQUEST_KEY)) {
        super.handleException(request, response, t);
        return;//from  w w w .ja v  a2  s.  c  om
    }

    Principal principal = request.getUserPrincipal();
    NuxeoPrincipal nuxeoPrincipal = null;
    if (principal instanceof NuxeoPrincipal) {
        nuxeoPrincipal = (NuxeoPrincipal) principal;
        // redirect to login than to requested page
        if (nuxeoPrincipal.isAnonymous()) {
            response.resetBuffer();

            String urlToReach = getURLToReach(request);
            log.debug(String.format("handleException#urlToReach#%s", urlToReach));
            Cookie cookieUrlToReach = new Cookie(NXAuthConstants.SSO_INITIAL_URL_REQUEST_KEY, urlToReach);
            cookieUrlToReach.setPath("/");
            cookieUrlToReach.setMaxAge(60);
            response.addCookie(cookieUrlToReach);
            log.debug(String.format("handleException#cookieUrlToReach#%s", cookieUrlToReach.getName()));
            if (!response.isCommitted()) {
                request.getRequestDispatcher(CAS_REDIRECTION_URL).forward(request, response);
            }
            FacesContext.getCurrentInstance().responseComplete();
        }
    }
    // go back to default handler
    super.handleException(request, response, t);
}

From source file:cec.easyshop.storefront.security.cookie.EnhancedCookieGeneratorTest.java

@Test
public void testServerSideCookieDefaultPath() {
    cookieGenerator.setCookieName("guid");
    cookieGenerator.setHttpOnly(true);//server side
    BDDMockito.given(request.getContextPath()).willReturn("/");
    cookieGenerator.addCookie(response, "cookie_monster");
    cookieGenerator.setUseDefaultPath(false);

    final Cookie expectedCookie = new Cookie("guid", "cookie_monster");
    expectedCookie.setPath("/");
    expectedCookie.setSecure(false);//ww  w .j  a  v  a2 s  .c om
    expectedCookie.setMaxAge(NEVER_EXPIRES);
    expectedCookie.setDomain("what a domain");

    Mockito.verify(response).addHeader(EnhancedCookieGenerator.HEADER_COOKIE,
            "guid=cookie_monster; Version=1; Domain=\"what a domain\"; Path=/; HttpOnly");
}