A secure password reset email contains a single-use link with a long random token that expires quickly, is sent only to the address on file, and is issued without revealing whether an account exists. The email should arrive within seconds, say plainly what happened and what to do if the request was not theirs, and never contain the password itself. Everything else in this guide is detail on those requirements.
Password reset is one of the most attacked flows in any product, and also one of the most common reasons users contact support. The design needs to satisfy two goals that pull in opposite directions: make recovery easy for real owners and make it useless to attackers. Follow the recommendations of the OWASP Forgot Password Cheat Sheet and adapt them to your own risk model.
How a secure reset flow works
- The user enters their email address on a forgot password form.
- The server responds with a generic message such as: If an account exists for that address, we have sent instructions. The response and timing are the same either way.
- If the account exists, the server generates a random token, stores a hash of it with an expiry time and the user ID, and queues the email.
- The user clicks the link, which carries the token. The server checks the hash, expiry and that it is unused.
- The user sets a new password. The server marks the token as used, updates the password hash, invalidates active sessions and sends a notification.
- The user signs in with the new password, ideally with multi-factor authentication where enabled.
Token design
Generate tokens with a cryptographically secure random generator, never from timestamps, user IDs or counters. Use at least 128 bits of entropy, which in practice means 16 random bytes or more, and 32 bytes is a comfortable choice. Store only a hash of the token in your database, so that a database leak does not give attackers working reset links. Make the token single use and tie it to one account. Expire it quickly. Thirty minutes to an hour is common, and the right value depends on how fast your emails arrive and how sensitive the account is. Issuing a new token should invalidate older ones.
import hashlib, secrets, datetime as dt
def create_reset_token(user_id, db):
raw = secrets.token_urlsafe(32) # 256 bits, URL safe
digest = hashlib.sha256(raw.encode()).hexdigest()
expires = dt.datetime.utcnow() + dt.timedelta(minutes=30)
db.execute("DELETE FROM password_resets WHERE user_id = %s", (user_id,))
db.execute(
"INSERT INTO password_resets (user_id, token_hash, expires_at, used) VALUES (%s, %s, %s, false)",
(user_id, digest, expires))
return raw # goes into the email link only, never logged
def verify_reset_token(raw, db):
digest = hashlib.sha256(raw.encode()).hexdigest()
row = db.fetchone(
"SELECT user_id FROM password_resets WHERE token_hash = %s AND used = false AND expires_at > now()",
(digest,))
return rowBecause the token is high entropy, a fast hash such as SHA-256 is acceptable for storing it; password hashing algorithms are needed for passwords, not for random tokens. Use constant-time comparison if you compare values in application code instead of in the database query.
Prevent account enumeration and abuse
- Return the same response and similar timing whether or not the address exists. Do the email work in a background queue so that response time does not give the answer away.
- Rate limit by IP address, by target account and by overall volume. Limit how many reset emails can be requested per hour for the same address, so that your system cannot be used to flood a victim.
- Add bot protection, such as a challenge, when you see abusive volume. See bot protection for forms.
- Send the email only to the address on file. Never let the request choose the destination.
- Set
Referrer-Policy: no-referreron the reset page, and keep third-party scripts and analytics off it, so the token does not leak in a referrer header. - Do not log full reset URLs, and exclude the path from request logs where possible.
- Make the link land on a page that asks for the new password and submits it by POST, not one that changes the password on a GET request.
Template to adapt
Subject: Reset your {{brand}} password
Hi {{first_name|there}},
We received a request to reset the password for the {{brand}} account
associated with this email address.
Reset your password: {{reset_url}}
This link works once and expires in 30 minutes.
If you did not request this, you can ignore this message. Your password
will stay the same. If you keep receiving these emails, contact
{{support_email}}.
For your security, we never ask for your password by email.
{{brand}} Security TeamKeep the message short with one clear button and a visible plain URL for clients that do not render the button. Avoid marketing content, images that carry key information and tracking that rewrites the reset URL through a third-party domain, because link wrapping makes phishing detection harder and can break the token. Turn off click tracking for reset links, or use a dedicated tracking domain you control. See click tracking domains. Compare with the broader patterns in reset email best practices and magic links and reset with one-time codes.
Deliver it fast and reliably
A reset email that arrives after five minutes is a failed reset. Users click the button again and again, which creates several tokens and more confusion. Send reset messages from a transactional stream that is separate from marketing, so that newsletter issues cannot delay them. See separating transactional and marketing streams. Authenticate the sending domain with SPF, DKIM and DMARC, using authenticating your sending domain, because unauthenticated reset emails are rejected by major providers or filtered to spam, and a spoofed reset email is also a phishing risk. Use a clear From name and a stable From address on your domain.
Track delivery events for these messages. A bounce on a reset request means the address is wrong or dead, and your application should handle that quietly rather than showing an error that exposes information. For delays and queued mail, see email delay causes and deferred and greylisted mail.
After the password is changed
- Mark the token used and delete any other outstanding tokens for the account.
- Invalidate existing sessions and remember-me tokens, since an attacker who knew the old password could still be signed in.
- Send a notification to the account email that the password was changed, with a way to report it.
- Do not sign the user in automatically in a way that bypasses multi-factor authentication.
- Consider notifying about reset requests in your security log for support to review.
Troubleshooting and common mistakes
| Problem | Cause | Fix |
|---|---|---|
| User never receives the reset email | Spam filtering, typo, bounce, delay | Check delivery events, authentication and queue age |
| Link says expired immediately | Clock drift or time zone mismatch, or link scanner consumed the token | Use UTC, sync clocks, and make the GET page non-destructive. See clock sync |
| Token fails after a click | Security scanner followed the link and used it | Only consume the token on the POST that sets the password |
| Attackers can learn which emails are registered | Different responses or timing | Use one response and background processing |
| Reset email floods a victim | No rate limit per account | Throttle by account and IP |
| Link in email is rewritten | Click tracking wraps the URL | Disable tracking for reset links |
| Multiple emails confusing users | Slow delivery causes repeat requests | Speed up sending and show a cooldown message |
| Tokens guessable | Weak random source | Use the platform CSPRNG with 128 bits or more |
Multi-factor authentication and recovery
If an account uses multi-factor authentication, a password reset must not become a way around it. Require the second factor after the reset, or require it before allowing the reset on high-risk accounts. Be equally careful with the recovery path for the second factor itself, because a weak recovery process undoes the benefit. For accounts with a recovery email or phone number, notify those channels as well when a reset is requested or completed. For internal and administrator accounts, consider requiring a manual approval or an additional check, since the cost of a takeover is much higher.
Next steps
Review your flow against the checklist above, then test it end to end: request a reset for a real and a nonexistent address, time both responses, let a token expire, try reuse, and check the email in the major mailbox providers. Re-test after every change to your email provider or authentication setup.
Send reset emails within seconds Use the email API or SMTP relay for transactional messages with delivery events.
References and further reading
Frequently asked questions
How long should a password reset link be valid?
Short, commonly 30 to 60 minutes. Choose a value that fits how quickly your email arrives and how sensitive the account is.
How do I stop attackers learning which emails are registered?
Show the same message and respond with similar timing whether or not the account exists, and send the email from a background queue.
Should I email the user their new password?
Never. Send a single-use link that lets the user choose a new password.
Why does the reset link say it has expired?
A link scanner may have used it, or clocks and time zones are mismatched. Only consume the token when the new password is submitted.
Should reset emails use click tracking?
No. Link rewriting can break tokens and makes phishing harder to spot, so disable tracking for reset links.