Wednesday, June 18, 2008

Remember User Login Via Cookies

How to persist user login via cookies if session has expired?, this is a question almost answered in most of nowadays web applications, So how can this be done?

The idea is simple, and can be summarized in these simple steps

1. add a new column in your users table called login_key or remember_token or any name you prefer of type string

2. whenever user tries to login and his login is successful, add in his cookies a cookie called anything ex: remember_token and let its value be a generated random string of length around 40 characters for better security which is our token, and save this token in the db with that user

3. now add, in any action you need to check in it whether this user already in system or guest, a snippet of code that checks if the person isn't logged in whether the request has a cookie with the name choosed before and if so, check the db looking for a user having that token, if found then this user is logged in as if he did that in the normal ordinary way

That's it, now you can use cookie to log user in if his session has expired. There are also some points you may need to take care of when using this technique

1. Make cookie expires after some time so that it gets created once again with new token

2. In order to provide extra security, add with that token another info about the user

No comments: