How-To Guide

How to Implement Secure Password Reset Flows

Build a password reset that resists enumeration and token theft: send a single-use, expiring token, always respond the same, and rotate sessions.

On this page

  1. Introduction
  2. Generate and store an unguessable token
  3. Respond identically to avoid enumeration
  4. Consume the token atomically
  5. Invalidate sessions and notify
  6. Test expiry, reuse, and enumeration
  7. Common pitfalls
  8. Conclusion

Introduction

Password reset is a high-value attack surface because it is the path to account takeover. A weak reset flow leaks which emails are registered, issues a token an attacker can guess or replay, or leaves old sessions valid after a password change. A secure flow treats every one of those as a requirement, not a nicety, because the reset endpoint can bypass the password entirely.

This tutorial builds a reset flow that generates an unguessable single-use token, responds identically whether or not the account exists, consumes the token atomically, and invalidates existing sessions. It ends with tests for expiry, reuse, and enumeration. The examples describe the flow in a language-agnostic way and use HTTP idioms.

Generate and store an unguessable token

The token must be unpredictable: generate it from a cryptographically secure random source with enough entropy, at least 128 bits, so brute force is infeasible. Treat the token as a bearer secret: whoever holds it can change the password, so it must be unguessable and must not be logged in full. Send it in the reset link and nowhere else.

Store only a hash of the token server-side, the same way you would store a password hash, so a read of the token table does not hand an attacker the ability to reset any account. The token row carries the user, an expiry in the near future, a single-use flag, and the hash. Reading a raw token out of the table is impossible because it is not there.

CREATE TABLE password_resets (
  id         bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  user_id    bigint NOT NULL,
  token_hash text NOT NULL UNIQUE,   -- store the hash, never the token
  expires_at timestamptz NOT NULL,
  used_at    timestamptz,
  created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX idx_password_resets_user ON password_resets (user_id) WHERE used_at IS NULL;

Respond identically to avoid enumeration

The reset request endpoint must not reveal whether an email is registered. An attacker feeds a list of emails and learns which are valid by the response. Return the same status, the same message, and the same success page whether or not the account exists. Only the actual account receives an email, but the caller cannot tell which from the response.

Respond the same regardless includes timing. If a registered account triggers a database lookup and an email send while an unknown one returns immediately, the difference in latency leaks existence. Move the work off the request path: acknowledge immediately and enqueue the lookup and send, so the response time does not depend on whether the account exists. This closes both the visible and the timing side channel.

async function requestReset(email, res) {
  // enqueue; do not await, so timing does not depend on account existence
  queue.publish('password-reset', { email });
  res.writeHead(202, { 'content-type': 'application/json' });
  res.end(JSON.stringify({ message: 'If the account exists, a reset link was sent.' }));
}

Consume the token atomically

When the user submits the token and a new password, verify the token inside a transaction: locate the row by its hash, check it is unused and unexpired, set the new password hash, and mark the token used, all in one transaction. Doing this atomically prevents a race where two requests use the same token, and prevents a replay where a used token is accepted again.

The single-use marker is what makes the token one-shot even if the link is leaked later; once used, it is dead. Expiry bounds the window in which a leaked link is useful, so set it short, such as an hour. Invalidate all other outstanding reset tokens for the user when one is used, so a previously issued link cannot be used after the password changed. Apply the new password only if it passes your strength policy, and hash it with the same algorithm as normal registration.

BEGIN;
UPDATE password_resets
SET used_at = now()
WHERE token_hash = $1 AND used_at IS NULL AND expires_at > now()
RETURNING user_id;
-- if a row returned, set the new password and invalidate other tokens
UPDATE users SET password_hash = $2 WHERE id = $3;
UPDATE password_resets SET used_at = now() WHERE user_id = $3 AND used_at IS NULL;
COMMIT;

Invalidate sessions and notify

Changing a password must invalidate existing sessions, or an attacker who already had a session keeps it despite the owner resetting the password. Bump a session version or a token generation counter on the user, so every previously issued session token is rejected. Force a re-login everywhere, and treat this as part of the reset, not an optional extra.

Notify the account owner by email that the password changed, with guidance if they did not do it. This gives the real owner a chance to react if an attacker completed a reset. The notification should not contain the new password or a new token; it is informational, so it adds awareness without adding a new attack surface.

-- bump the session generation so old sessions are rejected
UPDATE users SET session_generation = session_generation + 1 WHERE id = $1;

Test expiry, reuse, and enumeration

Test that a valid, unexpired, unused token resets the password. Test that the same token is rejected the second time, proving single use. Test that an expired token is rejected. Test that the request endpoint returns the same status and body for a registered and an unregistered email. Test that after a reset, a session issued before it is rejected, which proves session invalidation.

TOKEN=$(node scripts/issue-reset.mjs [email protected])
curl -s -o /dev/null -w '%{http_code}\n' -X POST -d "token=$TOKEN&password=NewPassw0rd!" http://localhost:3000/reset   # 200
curl -s -o /dev/null -w '%{http_code}\n' -X POST -d "token=$TOKEN&password=Again12345!" http://localhost:3000/reset   # 400, reused
# both a known and unknown email must get the same response body/status
curl -s -X POST -d '[email protected]' http://localhost:3000/forgot

Common pitfalls

Storing the token in plaintext so a table read grants resets, revealing account existence through the response or its timing, accepting a token more than once, a long expiry that widens the leak window, leaving old sessions valid after the change, and forgetting to invalidate other outstanding tokens are the recurring mistakes. Hashing the token, identical responses, atomic single use, a short expiry, and session invalidation address them.

Conclusion

A secure reset resists guessing, replay, and enumeration. Generate a high-entropy token, store only its hash with an expiry and single-use marker, respond identically whether the account exists, consume the token atomically, and invalidate sessions. Self-check by asserting a token cannot be reused, that expiry is enforced, and that both known and unknown emails get the same response. Then reset is a controlled path to regaining access, not a shortcut to takeover.

Sources: OWASP: Forgot password cheat sheet, OWASP: Authentication cheat sheet, RFC 4086: Randomness requirements for security.

FAQ

Should the reset link contain a signed token or a random one?
A random token stored server-side as a hash is simplest to reason about: the server controls validity, expiry, and single use, and the token reveals nothing. A signed token avoids storage but must carry its own expiry and a use check, which is easy to get wrong.
How do I avoid revealing registered emails?
Always return the same message and the same timing whether or not the account exists. Do the work asynchronously so a registered account does not take measurably longer, which would leak existence through timing.

Related Examples