You know those password reset links that are sent to you get when you forget your password? Well, some of them set a limit on how long you can use it before the link stops working. For the life of me, I couldn’t figure out why sites did this. Who cares how long it takes me to get around to resetting my password? Why not just make the same link work every time a person wants to reset his or her password?
So, I coded up a registration and password reset system for Domain Pigeon without setting a time limit on reset password links.
Last night, somewhat randomly, it hit me why this is a bad idea. It’s so obvious now that I don’t know why I didn’t think of it sooner.
If you reset your password in a public place, such as a library computer, the reset password URL will probably be stored in the browser navigation history. The next person who uses the computer might accidentally come across the “www.whatever.com/reset/…” URL and click it to see what happens. Surprise: it still works.
So how do you prevent this? You guessed it: a time limit.
Here’s how I implemented it for Domain Pigeon. When the customer requests a password reset email, store the time they requested it and then, to generate the URL, use a hash of the user’s email concatenated with the time they requested it. This’ll ensure that the URL is unique based on that specific request (aka a salt).
Then, when the customer clicks the link to reset his password, compare the current time to the time the link was sent and if it’s less than a specific amount of time, allow him to change his password. In pseudocode, this looks something like:
if hash(user.email + user.forgot_sent_at) = params[:hash] and user.forgot_sent_at + 2.hours > Time.now then
... yada yada yada
[Update: Note that the has function used here is a SHA-1 hash of the input concatenated with a secret key, so that the final product here = SHA(user.email + user.forgot_sent_at + long_random_string). Thank you to Artem for pointing out it needed to be clarified]
Lastly, after the password is changed, reset the stored time. That will prevent someone from changing the password twice using the same reset password link.
The only flaw I see with this method is for the person who clicks the link to reset his password and abandons it, because that’ll allow someone else to access the page and reset his password. Fortunately, this should be rare enough that it’s not a major problem. For extra security, set the time limit to five or ten minutes. After all, how many people request a reset password link and don’t access it within the next few minutes? For the few that do, they probably won’t mind the small annoyance in return for the extra security.
If anyone has any thoughts on this method or password reset algorithms in particular, please let me know.