I am developing an application and I’d like to offer the user a possibility to stay signed in forever. If he checks a box, his session should never end, unless he manually logs out or deletes the cookie. If he doesn’t, his session cookie will expire on closing the browser.
I considered three ways to realise this, but all of them contain pros and cons:
- Saving a cookie with the user name and his hashed password:
- Pro: The user can have multiple active sessions on different devices.
- Con: If the cookie gets leaked by third parties, they can regenerate his session at any time unless he changes his password.
- Generating a token which will be stored in the database and in the user’s cookies. Then compare them:
- Pro: As soon as the user logs out, the token will be randomized and all of his sessions will be destroyed. He will definitely be logged of.
- Con: The user can only log in forever with one device. As soon as he logs in from another device, accepting to be logged in forever, his other token will be overwritten.
- Only hypothetically: Save sessions forever on the server and give non-expiring cookies to the user.
- Con: This is probably not realistic, because you can’t store that much data in an efficient way.
I currently prefer the second way, because it does not seem to be as insecure as the first one and it’s easily implementable. But I am still not convinced of it and I have seen that there are proven frameworks which do it another way.
Could you imagine another way which is maybe even better? What’s your favorite and why?
Never save the password in a cookie. The second method is fine, and is how I think you’ll find most apps implement this feature. Note that the session storage doesn’t need to be a database. The cookie contains some unique (unguessable!) id, and this id points to some unique storage. It could be a text file in a directory somewhere, a database row, a JSON string in memcached, whatever.
Don’t store the token id as a column in the user table. Instead create a new cross table that allows more than one session per user. So, each device will have its own separate token, and thus, its own separate session which can be managed individually.
When a user logs out, you destroy only that one cookie and its associated session store. Any other sessions that the user has outstanding will remain untouched.