skip to content

API Tokens & HTTP Auth

Rails' own token tools: has_secure_token columns, generates_token_for and signed_id for expiring links, and the HTTP Token and Basic helpers. Interviewers probe raw versus digested storage.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In an Active Record model, what does has_secure_token :api_key provide, and when does Rails 8.1 fill in the value?

level: juniorimportance: must knowfreq 45%

answer

  1. a plain string column holds it
  2. SecureRandom.base58, 24 characters minimum
  3. regenerate_api_key goes through update!
  4. on: :initialize since load_defaults 7.1
  5. token:token generator adds a unique index

basics

~20 s

has_secure_token :api_key fills the api_key column with a random 24-character Base58 string and adds regenerate_api_key; under Rails 8.1 defaults the value is set when a new record is initialized, and it is stored as plain text.

solid answer

~40 s

`has_secure_token :api_key` expects a string column named `api_key` and fills it with `SecureRandom.base58(24)`; `length:` asks for more, and anything under 24 raises `ActiveRecord::SecureToken::MinimumLengthError`. It also defines `regenerate_api_key`, which calls `update!` with a new value, so it saves at once, runs validations and callbacks, and the old key stops matching immediately. With `load_defaults` 7.1 or later, `config.active_record.generate_secure_token_on` is `:initialize`, so `Account.new.api_key` is already present; the older `:create` behaviour filled it just before the first save. Rails adds no uniqueness check, so add a unique index, which `bin/rails generate model ... api_key:token` writes for you. The column holds the raw value: anyone who can read the table can use the keys.

code

ruby · 9 lines
ruby
# bin/rails console
account = Account.new(name: "Northwind Hooks")
account.api_key            # => already set: 36 Base58 characters
account.save!

old_key = account.api_key
account.regenerate_api_key # => true, saved through update!
Account.find_by(api_key: old_key) # => nil, the old key is gone
account.inspect            # api_key shows as [FILTERED]

go deeper

for a junior

Recall the column the macro needs, the 24-character Base58 default, the regenerate_ method it defines, and that the value is generated for you.

for a middle

Explain on: :initialize versus :create and the load_defaults 7.1 switch, why regenerate_ saves through update!, and why a unique index still matters.

for a senior

Show production awareness: the column holds raw keys, regeneration cuts over instantly with no grace period, and filter_parameters keeps the value out of logs and inspect.

for a principal

Weigh plaintext per-account keys from has_secure_token against digested or signed alternatives, and decide who owns key issuance, rotation and leak response.

## What the macro does `has_secure_token` is an Active Record class macro for **random, unguessable strings stored on a record**: API keys, invitation codes, webhook signing identifiers. On a webhooks relay service, each `Account` gets one key that its servers send with every API call: ```ruby class Account < ApplicationRecord has_secure_token :api_key, length: 36 end ``` The macro does three things: 1. Registers a callback that fills `api_key` with `generate_unique_secure_token`, which is `SecureRandom.base58(length)`, but only for a new record whose attribute is still blank. A value you assign yourself is kept. 2. Defines `regenerate_api_key`, which writes a fresh value with `update!`. 3. Checks the `length:` option once, when the class body runs. The attribute name defaults to `:token`, so a bare `has_secure_token` needs a `token` column. ## The options | Option | Default | Effect | |---|---|---| | attribute | `:token` | the string column to fill | | `length:` | `24` (`MINIMUM_TOKEN_LENGTH`) | characters of Base58; below 24 raises `ActiveRecord::SecureToken::MinimumLengthError` | | `on:` | `ActiveRecord.generate_secure_token_on` | `:initialize` uses an `after_initialize` callback; any other value, such as `:create`, a `before_` callback | Base58 leaves out look-alike characters (`0`, `O`, `I`, `l`), which helps when a person copies a key by hand. ## When the value appears | Setting | `Account.new.api_key` | Filled by | |---|---|---| | `load_defaults 7.1` or later (a new 8.1 app) | a 24-character string | `after_initialize` | | older defaults (`generate_secure_token_on = :create`) | `nil` | `before_create`, just before the first save | The 7.1 change means a form or a mailer can show the key before the record is saved. Apps upgraded from older defaults keep `:create` until their `load_defaults` (or `config.active_record.generate_secure_token_on`) moves. ## Rotating with regenerate_* `account.regenerate_api_key` is `update!(api_key: new_value)`: - it **saves immediately** and returns `true`; - it runs validations and callbacks, so an unrelated invalid attribute makes it raise `ActiveRecord::RecordInvalid`; - the old value is overwritten, so every client still sending it gets rejected from the next request on. There is no grace period; overlapping old and new keys is something you build yourself. ## Generating the model The `token` attribute type in the model generator wires everything up: ```bash bin/rails generate model ApiKey account:references token:token ``` The migration gets `t.string :token` plus `add_index :api_keys, :token, unique: true`, and the model gets `has_secure_token`. The macro itself adds no uniqueness validation; the unique index is the guard against the unlikely collision and makes `ApiKey.find_by(token:)` an index lookup. ## What sits in the database The column holds the **raw key**. A copied table, backup or replica is a list of working credentials, and support staff can read keys in a console. A new app's `config/initializers/filter_parameter_logging.rb` filters partial matches such as `:token` and `:_key`, and Active Record adds that list to `filter_attributes`, so the value shows as `[FILTERED]` in logs and `inspect` output. That hides it from logs, not from the table. Storing only a digest of the key is a design choice `has_secure_token` does not make for you. ## Common misreadings - **"It hashes the token."** It stores the value as generated. - **"It validates uniqueness."** It does not; use the unique index. - **"regenerate only assigns."** It saves through `update!`. - **"Shorter keys are fine for internal use."** Below 24 characters the macro refuses to load. ## Where it fits among Rails' token tools - `has_secure_token` **stores** a random value, so the record can be found by it later and the value can be replaced with `regenerate_*`. That suits long-lived credentials a client keeps, such as the relay's per-account API keys. - `generates_token_for` and `signed_id` **store nothing**: they sign a payload and verify it when it returns. They suit links that should expire, such as an email-change confirmation. - `has_secure_password` is a different thing again: a bcrypt digest of a secret the user chose. ## A short checklist for an API-key column 1. Generate it with the `token` attribute type so the unique index comes with it. 2. Decide the length once; 24 is the floor, and more costs nothing. 3. Keep `filter_parameters` matching the column name so it never reaches logs. 4. Give owners a way to call `regenerate_api_key`, and tell them the old key dies at once. 5. Treat database access as access to every key, because the column holds them raw.

  • Why is a unique index still worth adding when the token is random?
    `has_secure_token` adds no uniqueness validation, and Rails' own documentation for the macro recommends an index. A collision among 24 Base58 characters is vanishingly unlikely, but the index makes the database the final guard and turns `find_by(api_key:)` into an index lookup. The model generator's `token` type writes `add_index ..., unique: true` for you.
  • Does has_secure_token keep the key out of logs?
    Not by itself. A new app's `filter_parameter_logging.rb` filters partial matches such as `:token` and `:_key`, so a parameter named `api_key` is masked in request logs, and Active Record copies that list into `filter_attributes`, so `inspect` shows `[FILTERED]`. The value is still plain text in the table.

  • has_secure_token stores a hash of the token, so a table leak is harmless.
  • has_secure_token adds a uniqueness validation, so no unique index is needed.
  • regenerate_api_key only assigns a new value; you still have to call save.
  • In a new Rails 8.1 app, Account.new.api_key stays nil until the first save.
  • has_secure_token :api_key, length: 12 just produces shorter keys.

Assumes Rails 8.1 with load_defaults 7.1 or later, where generate_secure_token_on is :initialize; the framework's own fallback is :create, which fills the token just before the first save.

open as a page

In a Rails API controller, how do you authenticate each request by a per-account API key with authenticate_or_request_with_http_token?

level: middleimportance: must knowfreq 45%

basics

~10 s

Call authenticate_or_request_with_http_token from a before_action; Rails parses an Authorization: Bearer or Token header, yields the token to your block, and when the block returns a falsy value answers 401 with a WWW-Authenticate: Token challenge.

open as a page

In a Rails controller, what does http_basic_authenticate_with name:, password: do, and when is it the right guard?

level: juniorimportance: should knowfreq 32%

basics

~20 s

http_basic_authenticate_with is a controller class macro that adds a before_action checking one fixed name and password from HTTP Basic credentials and answering 401 with a Basic challenge otherwise; it suits a staging gate or a small internal page.

open as a page

In Rails, when would you hand out record.signed_id(expires_in:, purpose:) instead of a generates_token_for token, and why can't you revoke one early?

level: seniorimportance: should knowfreq 25%

basics

~20 s

signed_id signs only the record's id with an optional expiry and purpose, so it suits short-lived links that need no revocation; with no record state in it, a leaked one works until it expires unless every link's purpose changes.

open as a page