skip to content

In Rails 8.1, how does has_secure_password's password_reset_token work without a token column, and what makes a reset link stop working?

level: middleimportance: should knowfreq 45%

answer

  1. a signed message, not a stored row
  2. id plus the last 10 salt characters
  3. 15 minutes by default
  4. reset_token: { expires_in: } in 8.1
  5. bang finder raises InvalidSignature

basics

~20 s

password_reset_token is a signed, expiring message carrying the user's id and part of the password's bcrypt salt. It stops working after 15 minutes by default, or as soon as the password changes, because the salt it embedded no longer matches.

solid answer

~40 s

With `has_secure_password` on an Active Record model, Rails declares `generates_token_for :password_reset, expires_in: 15.minutes` with a block returning the last 10 characters of the password salt. `user.password_reset_token` signs `[id, salt_fragment]` with an expiry; nothing is stored. `User.find_by_password_reset_token(token)` verifies the signature and expiry, loads the user and compares the embedded fragment with the current salt, returning `nil` on any mismatch, while `find_by_password_reset_token!` raises `ActiveSupport::MessageVerifier::InvalidSignature`. Setting a new password generates a new salt, so every outstanding link dies at once. Rails 8.1 adds `has_secure_password reset_token: { expires_in: 1.hour }`; `reset_token: false` turns it off. The generated `PasswordsController` uses the bang finder, rescues `InvalidSignature`, and destroys all the user's sessions after a successful reset.

code

ruby · 9 lines
ruby
class User < ApplicationRecord
  has_secure_password reset_token: { expires_in: 30.minutes }
end

token = user.password_reset_token
User.find_by_password_reset_token(token)  # => user
user.update!(password: "new secret", password_confirmation: "new secret")
User.find_by_password_reset_token(token)  # => nil, the salt changed
User.find_by_password_reset_token!(token) # raises ActiveSupport::MessageVerifier::InvalidSignature

go deeper

for a junior

Recall the three method names, the 15-minute default, and that the generated controller signs the user out of every session after a reset.

for a middle

Explain the signed payload of id plus salt fragment, why a password change voids every outstanding link, and which finder returns nil versus raising.

for a senior

Account for deliver_later starting the clock in the job, the unrescued RecordNotFound, reusable links within the window, and secret rotation voiding tokens.

for a principal

Weigh stateless signed tokens, which cannot be revoked one by one, against a stored hashed token that can, given what the product's support process needs.

## No table, no column A classic reset flow stores a random token (or its hash) on the user row and clears it after use. Rails' `has_secure_password` takes a **stateless** route instead: the token is a **signed message**, and validity is recomputed from the user's current data every time it is presented. When `has_secure_password` is declared on a class that responds to `generates_token_for` (every Active Record model does; a plain Active Model class does not), it runs the equivalent of: ```ruby generates_token_for :password_reset, expires_in: 15.minutes do password_salt&.last(10) end ``` and defines three methods: | Method | Kind | Returns | |---|---|---| | `user.password_reset_token` | instance | a signed token string | | `User.find_by_password_reset_token(token)` | class | the user, or `nil` | | `User.find_by_password_reset_token!(token)` | class | the user, or raises | It also defines `password_reset_token_expires_in`, which the generated mailer uses to tell the reader how long the link lasts. ## What is inside the token The token is produced by the model's message verifier (the application's verifier named `active_record/token_for`, derived from `secret_key_base`). Its payload is `[user.id, last_10_characters_of_salt]`, it carries an expiry, and its **purpose** string includes the class name, `password_reset` and the `expires_in` value. Signing makes it tamper-proof; it is not encrypted, so treat it as a bearer credential in a URL. ## What makes a link stop working 1. **Expiry.** After 15 minutes by default the signature check fails. 2. **The password changed.** Setting `password=` creates a new bcrypt hash with a **new salt**, so the embedded fragment no longer matches. One reset therefore kills every older link for that user, including the link just used. 3. **`expires_in` changed.** The duration is part of the purpose, so changing it invalidates links already sent. 4. **The signing secret changed.** Rotating `secret_key_base` without keeping the old secret invalidates outstanding tokens. Until one of those happens, a token is **reusable**: two reset emails sent a minute apart both work, and the first one used kills the other. ## The two finders - `find_by_password_reset_token` returns `nil` for a bad signature, an expired token, a changed salt or a deleted user. - `find_by_password_reset_token!` raises **`ActiveSupport::MessageVerifier::InvalidSignature`** for an invalid, expired or stale token, and **`ActiveRecord::RecordNotFound`** if the token is valid but the user row is gone. ## How the generated flow uses it 1. `PasswordsController#create` looks up `User.find_by(email_address: params[:email_address])` and, if found, calls `PasswordsMailer.reset(user).deliver_later`. It always redirects with the same notice, whether or not the address exists. Rails 8.1's output rate-limits this action to 10 requests per 3 minutes. 2. The mailer view links to `edit_password_url(@user.password_reset_token)` and prints `distance_of_time_in_words(0, @user.password_reset_token_expires_in)`. With `deliver_later`, the view renders inside the job, so the 15 minutes start when the job runs. 3. `before_action :set_user_by_token` calls `User.find_by_password_reset_token!(params[:token])` and rescues `InvalidSignature` with a redirect and "Password reset link is invalid or has expired." `RecordNotFound` is not rescued, so a deleted user's link falls through to Rails' 404 handling. 4. `update` calls `@user.update(params.permit(:password, :password_confirmation))`; on success it runs `@user.sessions.destroy_all`, signing the user out everywhere. On any validation failure it redirects back to `edit_password_path(params[:token])` with "Passwords did not match.", whatever the actual error was, for example a password over 72 bytes, so a team that adds length rules usually changes this branch to re-render the form with the model's errors. The generated `PasswordsControllerTest` exercises the whole path: it posts a known and an unknown address, asserts an enqueued email only for the first, and checks that an invalid token redirects to `new_password_path`. A mailer preview, `PasswordsMailerPreview#reset`, renders the email at `/rails/mailers/passwords_mailer/reset` in development. ## Configuring it - **Rails 8.1** adds `has_secure_password reset_token: { expires_in: 1.hour }`; before 8.1 the 15-minute default could not be changed through this macro. - `has_secure_password reset_token: false` defines none of the reset methods. - A second password attribute gets its own token: `has_secure_password :recovery_password` defines `recovery_password_reset_token`.

  • Why does the generated PasswordsController#create redirect with the same message whether or not the email exists?
    It sends the mail only when `User.find_by(email_address:)` finds someone, but always redirects with "Password reset instructions sent (if user with that email address exists)." A different message for unknown addresses would let anyone probe which addresses have accounts.
  • A user clicks a reset link 20 minutes after requesting it on a default setup; what does the generated app do?
    `find_by_password_reset_token!` raises `ActiveSupport::MessageVerifier::InvalidSignature` because the token is older than the 15-minute default. `set_user_by_token` rescues it and redirects to `new_password_path` with "Password reset link is invalid or has expired.", so the user requests a new one.

  • The reset token is stored in a password_reset_token column on users.
  • has_secure_token generates the reset token and regenerate_token revokes it.
  • A used reset link stays valid until its 15 minutes run out.
  • find_by_password_reset_token! returns nil for an expired token.
  • The reset expiry can only be changed by overriding generates_token_for.

Assumes Rails 8.1; the reset_token: { expires_in: } option is new in 8.1, and the default expiry stays 15 minutes.