Cookie not being read

2.7k views Asked by At

I implemented "Remember me" functionality in my web app. I did this using a cookie that contains username/password encrypted using RSA.

I add the cookie when I login; if then I logout (without closing browser) the cookie is read ok and in the login page I see username/pass already typed. But if I close the browser; or close tab and run the application again, when the cookies are read, the only cookie that is read is the JSESSIONID. the cookie with the credentials is not in the array returned by ((HttpServletRequest)facesContext.getExternalContext().getRequest()).getCookies(­); even though I can see it in the browser. why is that?

This is the code that creates the cookie:

String credentials = username + "?" + password;
Cookie c = CookieHandler.getInstance().createCookie("vtcred", credentials, rememberMe);
FacesContext facesContext = FacesContext.getCurrentInstance();
((HttpServletResponse) facesContext.getExternalContext().getResponse()).addCookie(c);

and method createCookie:

public Cookie createCookie(String name, String value, boolean rememberMe) {
        value = encript(value);
        Cookie credCookie = new Cookie(name, value);
        credCookie.setHttpOnly(true);
        if(rememberMe) {
            credCookie.setMaxAge(86400);
        }
        else {
            credCookie.setMaxAge(0);
        }
        return credCookie;
    }

Edit: I am setting the cookie's max age to one day; and in the browser I can see that the cookie expires tomorrow, so that's not the problem

Thanks in advance, Damian

edit2: this is very odd, but it seems to be working now. I'll keep testing it and notify. Thanks.

2

There are 2 answers

0
damian On BEST ANSWER

I found why sometimes a cookie is not read. It has to do with the path attribute.

If anyone is having this issue, set the path of the cookie, like this:

Cookie c = new Cookie("name", "value");
cookie.setMaxAge(86400);
cookie.setPath("/");

Regards

1
Kal On

You might want to set the cookie with an expiration date. If you dont , it will only last as long as the browser session.