2

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.

damian
  • 4,024
  • 5
  • 35
  • 53
  • Storing the username and password in a cookie, encrypted or not, doesn't sound like a very good idea – Matti Virkkunen May 02 '11 at 19:51
  • Can you post the code where you are setting the cookie? – Kal May 02 '11 at 19:59
  • code added @Kal @Matti Virkkunen, I know it's not a good idea, but in my case it's the only choice I've got because the web app I'm developing is just the web interface for an existing system. I'm using web service calls to the app server (which contains data base and most of the logic) – damian May 02 '11 at 20:27

2 Answers2

3

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

damian
  • 4,024
  • 5
  • 35
  • 53
0

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

Kal
  • 24,724
  • 7
  • 65
  • 65
  • I'm sorry I forgot to say that. I am setting the maxAge to one day with the following code: credCookie.setMaxAge(86400); and this is working because when I see the cookie in the browser, in "Expires" field I see tomorrow's date. – damian May 02 '11 at 19:58