Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cookies for "Remember me" in JSF

Tags:

java

cookies

jsf

I have a login page, and I want to add the "Remember me" feature; so that if user logs out and opens the page again, his username and password are loaded. For this, when user logs in (and "remember me" is checked") I save the following cookies:

FacesContext facesContext = FacesContext.getCurrentInstance();
Cookie userCookie = new Cookie("vtusername", username);
userCookie.setMaxAge(3600);
((HttpServletResponse) facesContext.getExternalContext()
       .getResponse()).addCookie(userCookie);
Cookie passCokie = new Cookie("vtpassword", password);
passCokie.setMaxAge(3600);
 ((HttpServletResponse) facesContext.getExternalContext()
       .getResponse()).addCookie(passCokie);

The problem is that later (in the same session) I read the cookies and I see that maxAge = -1; even though I'm setting it to 3600... why is that? Another issue: if I set the cookie secure with userCookie.setSecure(true) then I can't read it (it dissapears).

Another question: since a password is being stored in a cookie, should I encrypt it some how? what is the best practice?

Thanks in advance

like image 703
damian Avatar asked Apr 29 '11 19:04

damian


1 Answers

The problem is that later (in the same session) I read the cookies and I see that maxAge = -1; even though I'm setting it to 3600... why is that?

Because the browser doesn't send the maxage back. It only sends the cookie name=value back. The maxage is only stored in the browser. You can check it in the cookie viewer/editor of the webbrowser itself. In Firefox for example, you can check all cookies by Tools > Options > Privacy > Remove individual cookies. Enter the domain (e.g. localhost) to see the cookies.

Another issue: if I set the cookie secure with userCookie.setSecure(true) then I can't read it (it dissapears).

It only works when the request/response is served over HTTPS instead of HTTP. Also, when the request is already served over HTTPS, it will already default to secure=true.

Another question: since a password is being stored in a cookie, should I encrypt it some how? what is the best practice?

Do not store the raw name/password in two cookies. Apart from that this can easily go in just a single cookie, this is a very bad idea and easily hackable. Use a single cookie with an autogenerated long, unique and impossible-to-guess value. Store this value along with the user ID in a database in the server side. When someone visits your site with this cookie, but the user is not logged in yet (i.e. there's no User object in session), then you can do the automatic login.

See also:

  • How to implement "Stay logged in"?
  • How to keep a user logged in?
like image 155
BalusC Avatar answered Nov 05 '22 11:11

BalusC