Generating secure tokens for forgot password and remember me cookie
22 Oct 2014
I was made team lead of a project, that saved passwords in plain text in cookies for remember me, verification email just contained primary key and forgot password just sent the password in mail.
In short: It was crazy and looked like a sophomore university project. I had to do something to secure most of it. So I decided to generate tokens for such data and sharing code here for help of others.
Why use tokens?
Let’s assume we have a url http://example.com/verify.php?id=2132 which verifies email id firstname.lastname@example.org and auto logins user with id 2132, once url is hit. A major security blunder is that if I hit http://example.com/verify.php?id=2133, http://example.com/verify.php?id=2134 and so on… I can easily verify all emails in your database and login.
Another example is remember me cookie, people save user ids in cookies and check for user ids in server side script to validate and login users without password. If I make a cookie with any user’s id I can easily login.
Fetch user id from database using user supplied data in cookies, post or get, such that user can’t guess or access anyone else’s user id.
After a lot of research and thinking I came up with this solution:
Generate a cryptographically secure random token and save it against an expire time and desired user id.
When a token is supplied via REQUEST, pass token to a function which checks if token exists and is not expired so returns user id otherwise returns false.
This makes sure that identity tokens are random and can’t be guessed by anyone.
Note:This isn’t just a copy/paste code, you have to understand it and at least modify set and get methods of TempTokens class to make it work properly with your database.
When properly used, these can save you a lot of embarrasment that comes from someone hacking into your site. If you have any other questions regarding secure web apps or feedback for my approach, do let me know in comments.