Java servlet remember me with cookies

I need to implement a simple “remember me” option in a Java servlet using cookies without using any advanced frameworks.

Firstly, when I log in, I create a cookie and send it in response to the browser (client). The value to be stored in the cookie is simply a hash of the username and password.

How do I manage an incoming request from a browser by sending a cookie? My approach is to check between registered users if there is any user having a hash on behalf of the user + password equal to the value in the cookie? Is this approach right?

In addition, I did not quite understand what the expiration mechanism is. Does the browser delete the cookie when it has expired, but this is not the case, how can I check if the cookie has expired?

+4
source share
1 answer

Until you use HTTPS, the method you offer is extremely unsafe. I would suggest creating some kind of session token (for example, use java.util.UUID.randomUUID() ) and set it as a cookie and save it somewhere on the server side so that later you can identify the user associated with this identifier cookie session.

This gives you the option to reset a specific session cookie if you believe that some kind of fraud is occurring and there is no direct connection between the username / password and the cookie you use. But note: this method is still vulnerable to a man-in-the-middle attack.

Regarding the expiration: yes, the cookie becomes invalid and can be deleted by the browser if it has expired. But you can set a cookie on something in the year 3000, so that it lives forever.

+4
source

All Articles