Generate secret code for password reset

22,755

Solution 1

Yes, you should

  1. Generate a random reset token. See e.g. this answer.
  2. Store it in the database (possibly with an expiry time)
  3. Send e-mail to the user with the reset token.
  4. User visits the reset password page with the reset token in the query string.
  5. Check the database to see the user associated with the reset token and if the expiry time hasn't passed.
  6. If everything checks out, allow the user to reset the password and delete the reset token from the database.

There seems to be a lot a confusion about the generation of the reset token (or whatever you want to call it). Please read the answer I've linked to and don't reinvent the wheel with hashes and weak seeds.

Solution 2

Just using some hash function with user's ID, user's salt (you salt the user's password, right?) and pseudo-random data should be OK:

$pwd_reset_hash = hash ( 'sha256' , $user_id . $user_salt, uniqid("",true));

Store it in the DB (together with time of request) as the reset key for this user

 user_id  pwd_reset_hash  time_requested  
===========================================  
 123      ae12a45232...   2010-08-24 18:05

When the user tries to use it, check that the hash matches the user and that the time is recent (e.g. "reset code is valid for 3 hours" or something like that)

delete it from DB when used or expired

Solution 3

The way to go is indeed generate some kind of random thing and storing it in the database. As soon as the password is changed you remove the relevant record from the table so that the link cant be used again.

  • Mail the url to the user, including the "token".
  • If the link is visited, check if the token exists, allow user to change password
  • Delete the token from the database.

As said already in the other responses, doing a SHA1 or an MD5 of the userid, combined with microtime and some salt string is usually a safe bet.

Share:
22,755
chrizonline
Author by

chrizonline

Software engineer. Avid traveller. Hobby photographer.

Updated on November 25, 2020

Comments

  • chrizonline
    chrizonline over 3 years

    I'm doing a module which allow users to reset password. I noticed how most websites they provide a confirmation link which contain query string that has a unique hash.

    My question is: How can I generate this unique hash each time the same user request forgot password? Should I store this hash in database and use it for verification later on? Will it be safe? Or should I create some sort of algorithm which generate one-time password? How can I generate a OTP?