Persistent Login Cookies Done Right
Best Practices for Keeping Your Visitors Logged-InPublished Apr 18, 2006 by lobo235
Last updated on Jul 3, 2007
Most of the websites I use allow you to setup an account so you can have access to member-only functions such as commenting on posts, posting photos, or customizing the way the site looks. I absolutely hate it when I am not offered a 'remember me' option when I log in to one of these sites. It is such a pain to log in every single time I visit a page especially when it is a site that I use frequently throughout the day. I would imagine that most website visitors out there share this same pet-peeve of mine so it is important to address this issue on your own websites.
The method that I prefer to use is a lot more secure than the above method. We will still use a cookie to remember the logged in users but we will not store the username/password in that cookie. Instead we're going to store a random code in the cookie along with the user's unique id. We will store that same code in a database somewhere along with the username or id for that user. Each time the user logs in using that cookie we are going to generate a new random code and update the user's cookie and our database with the new code. This works in much the same way that newer garage door openers and car alarms work. Each time the code is used to log in a new code is generated for the next use. This method is much more secure than other methods.
Multiple cookies can be set for an individual user in a different browser or on a different machine which allows them to stay logged in wherever they want. Because the user might delete their cookie at some point or another you should set a timestamp in your database for each cookie you create. This allows you to go through and clean out any cookies that are really old. I also like to store the timestamp each time a particular cookie is used. If a user is still using the cookie I don't delete it from the database even if it was created a long time ago.
In order for a third party to gain access to the site using the user's credentials they will have to figure out that you are changing the code each and every time. Most hackers/wrongdoers will give up when they see that you have done something different to keep your user's logged in. This method (or any other method) for keeping users logged in is not 100% safe or secure. It is my recommendation that when a user has been authenticated using a cookie you should not allow them to access critical areas of their account without first entering their password. For example, if the user wants to change their email address or password you should have them type in their password first if they were authenticated using a cookie-based method.
0 comments for this article.
PHP Application Management