In Rails, how does generates_token_for :email_change, expires_in: 30.minutes with a block produce links that expire and stop working once used?
answer
- nothing stored; the token is signed
- payload is the id plus block JSON
- block re-run on lookup must match
- find_by_token_for nil, the bang raises
- changing expires_in voids old tokens
basics
~10 sgenerates_token_for signs the record's id plus the block's current value with an expiry; find_by_token_for re-runs the block on lookup, so once that value changes, for example when unconfirmed_email is cleared, the link stops working.
solid answer
~40 s`generates_token_for :email_change, expires_in: 30.minutes do unconfirmed_email end` defines a purpose; `user.generate_token_for(:email_change)` returns a string signed by an application message verifier that carries the record's id and the block's value as JSON, with the expiry built in. Nothing is written to the database. `User.find_by_token_for(:email_change, token)` checks the signature, purpose and expiry, loads the record, re-runs the block and returns the user only if the value still matches, otherwise `nil`; `find_by_token_for!` raises `ActiveSupport::MessageVerifier::InvalidSignature`, or `ActiveRecord::RecordNotFound` if the row is gone. Confirming the change clears `unconfirmed_email`, so a used link fails, and so does an older link once a different address is requested. The token is signed, not encrypted, so the block value is readable, and because `expires_in` is part of the purpose, changing it voids every outstanding token.
code
ruby · 18 lines# app/mailers/user_mailer.rb
def email_change
@token = params[:user].generate_token_for(:email_change)
mail to: params[:user].unconfirmed_email
end
# app/controllers/email_changes_controller.rb
class EmailChangesController < ApplicationController
def show
user = User.find_by_token_for(:email_change, params[:token])
if user
user.confirm_email_change!
redirect_to root_path, notice: "Email address updated."
else
redirect_to root_path, alert: "That link is invalid or has expired."
end
end
endgo deeper
Recall the three methods: generates_token_for declares a purpose, generate_token_for makes a token, and find_by_token_for returns the record or nil.
Explain the payload of id plus block JSON, why the block runs again on lookup, how expiry works, and what the bang finder raises in each failure case.
Show you pick a block that changes when the link is used, keep secrets out of it, and know that changing expires_in or secret_key_base voids every outstanding link.
Weigh stateless signed links against stored, individually revocable tokens for each flow, and agree link lifetimes with product and security owners.
## Defining a purpose `generates_token_for` (Active Record, since Rails 7.1) declares a **purpose** for stateless, signed tokens on a model. A webhooks relay lets account owners change their contact address; the new address must be confirmed through an emailed link: ```ruby class User < ApplicationRecord generates_token_for :email_change, expires_in: 30.minutes do unconfirmed_email end def confirm_email_change! update!(email_address: unconfirmed_email, unconfirmed_email: nil) end end ``` Three methods work together: - `generates_token_for(purpose, expires_in: nil, &block)` registers the definition on the class. - `user.generate_token_for(:email_change)` returns a token string. - `User.find_by_token_for(:email_change, token)` and `find_by_token_for!` turn it back into a record. ## What the token contains | Part | Source | |---|---| | record id | `model.id` | | block value | the block run with `instance_eval` on the record, as JSON | | purpose | the class name, the purpose and `expires_in`, joined | | expiry | now plus `expires_in`, when one is given | | signature | `Rails.application.message_verifier("active_record/token_for")`, keyed from `secret_key_base` | **No table stores it.** The token is self-contained; verifying it needs only the secret and the record. ## Looking it up `find_by_token_for` runs these checks in order and returns `nil` at the first failure: 1. The signature is valid and the purpose matches this definition. 2. The token has not expired. 3. A record with the embedded id exists. 4. The block, run again on that record **now**, returns the same JSON as when the token was made. | Method | Bad, expired or stale token | Valid token, record deleted | |---|---|---| | `find_by_token_for` | `nil` | `nil` | | `find_by_token_for!` | raises `ActiveSupport::MessageVerifier::InvalidSignature` | raises `ActiveRecord::RecordNotFound` | Both are also relation methods, so `User.where(suspended: false).find_by_token_for(:email_change, token)` only finds an active user. An unknown purpose raises `KeyError`. ## Making the link single-use Step 4 is what makes links die. Choose a block whose value changes when the action happens: 1. The owner requests a change; the app sets `unconfirmed_email` and mails a link. 2. Clicking it finds the user and calls `confirm_email_change!`, which clears `unconfirmed_email`. 3. A second click re-runs the block, gets `nil`, finds no match, and fails. 4. Requesting yet another address changes the block value, so older links fail too. Common block choices: `unconfirmed_email` for confirmations, part of `password_salt` for resets (Rails' own example), a `last_sign_in_at` for magic links. ## What invalidates every token at once - Changing `expires_in`, because it is part of the purpose string. - Renaming the purpose or the model class. - Rotating `secret_key_base` without keeping the old secret for verification. ## Mistakes to avoid - **Putting secrets in the block.** The token is signed, not encrypted; the block value is readable JSON inside it. - **Expecting per-token revocation.** There is no row to delete. You revoke by changing what the block returns. - **Omitting `expires_in`.** Without it the token never expires; only the block can stop it. ## Testing the link A request test can cover every failure path with Active Support's time helpers: 1. Generate a token with `user.generate_token_for(:email_change)` and `get email_change_path(token)`; expect the address to change. 2. Request the same path again; expect the "invalid or expired" branch, because `unconfirmed_email` is now `nil`. 3. Generate a fresh token, call `travel 31.minutes`, and expect the expired branch. 4. Generate a token, set `unconfirmed_email` to another address, and expect the old token to fail. ## Choosing the expiry and the block together - The **expiry** bounds how long a leaked link is useful even if nothing changes on the record. - The **block** bounds how many times it is useful: once the action changes the value, the link is spent. - A link that needs both, such as an email change, sets both; a link that is harmless to reuse, such as an unsubscribe link, often sets neither.
- How would you revoke one user's outstanding email-change links before they expire?Change what the block returns. Clearing or replacing `unconfirmed_email` makes every earlier token for that user fail the comparison in `find_by_token_for`. There is no per-token row to delete, so revocation always goes through the record's own state.
- Why does deploying expires_in: 1.hour instead of 30.minutes break links already sent?The expiry duration is folded into the token's purpose together with the class name and the purpose name, so a token signed under the 30-minute definition no longer verifies under the 1-hour one. Make the change when few links are in flight, or accept that recent ones must be requested again.
- generates_token_for saves each token in the database so it can be revoked.
- A generates_token_for token is encrypted, so the block value stays private.
- Once signed, the token stays valid until expires_in, whatever changes on the record.
- find_by_token_for raises an exception when the token is invalid.
- Changing expires_in only affects tokens generated after the deploy.
Assumes Rails 8.1; generates_token_for, generate_token_for and find_by_token_for arrived in Rails 7.1, so older apps built this with signed_id or a stored token column.