In a Rails API controller, how do you authenticate each request by a per-account API key with authenticate_or_request_with_http_token?
answer
- Token or Bearer prefix accepted
- block receives token and options
- truthy return means authenticated
- 401 with WWW-Authenticate: Token realm
- ActionController::API needs the module included
basics
~10 sCall 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.
solid answer
~40 s`authenticate_or_request_with_http_token` comes from `ActionController::HttpAuthentication::Token::ControllerMethods`, which `ActionController::Base` includes and `ActionController::API` does not, so an API-only controller includes it explicitly. In a `before_action`, Rails reads the `Authorization` header, accepts the `Token` or `Bearer` prefix, and yields the token plus an options hash (from `Token token="abc", nonce="def"`). Return the account, for example `Account.find_by(api_key: token)`; a truthy value lets the action run and is also the method's return value. A missing header or a falsy result renders 401 with `WWW-Authenticate: Token realm="Application"` and the body `HTTP Token: Access denied.`, which halts the chain. For a JSON error, call `authenticate_with_http_token`, which returns `nil` instead of responding, and render your own 401.
code
ruby · 12 linesclass Api::BaseController < ActionController::API
include ActionController::HttpAuthentication::Token::ControllerMethods
before_action :authenticate_account!
private
def authenticate_account!
authenticate_or_request_with_http_token("Webhooks Relay") do |token, _options|
@current_account = Account.find_by(api_key: token)
end
end
endgo deeper
Recall that the helper reads the Authorization header, yields the token to your block, and that a falsy return sends a 401 challenge.
Explain the Token and Bearer prefixes, the options hash, the difference from authenticate_with_http_token, and why API controllers must include the module.
Show production habits: JSON 401s through authenticate_with_http_token, an indexed lookup, keys masked in logs, and request tests built with Token.encode_credentials.
Weigh Rails' built-in token helpers against running an OAuth provider for partner access, and set the policy for issuing, scoping and revoking per-account keys.
## Three methods, one module `ActionController::HttpAuthentication::Token::ControllerMethods` gives a controller three instance methods: | Method | What it does | |---|---| | `authenticate_or_request_with_http_token(realm = "Application", message = nil) { \|token, options\| ... }` | yields the token; returns the block's value, or renders a 401 challenge | | `authenticate_with_http_token { \|token, options\| ... }` | yields the token; returns the block's value, or `nil` when there is no token | | `request_http_token_authentication(realm = "Application", message = nil)` | renders the 401 challenge on its own | `ActionController::Base` includes the module, along with the Basic and Digest ones. `ActionController::API` leaves all three out to stay small, so an API controller adds `include ActionController::HttpAuthentication::Token::ControllerMethods`; without it the call raises `NoMethodError`. ## What Rails parses 1. It reads `request.authorization` and needs it to start with `Token ` or `Bearer `. The match is case-sensitive, so a header beginning `bearer` yields no token. 2. It strips the prefix and splits the rest on `,`, `;` or tab. If the first part is not `token=...`, it is treated as the token, which is how `Bearer abc` works. 3. It removes surrounding quotes and returns the token plus the other pairs as an options hash with indifferent access. 4. A blank token means the block is never called. So `Authorization: Bearer abc` and `Authorization: Token token="abc"` both reach the block as `"abc"`, and `Token token="abc", nonce="def"` also yields `options[:nonce] == "def"`. ## Wiring it into the relay's API ```ruby class Api::BaseController < ActionController::API include ActionController::HttpAuthentication::Token::ControllerMethods before_action :authenticate_account! private def authenticate_account! authenticate_or_request_with_http_token("Webhooks Relay") do |token, _options| @current_account = Account.find_by(api_key: token) end end end ``` Every controller under `Api::` inherits the filter. The lookup goes through the unique index on `api_key`, the column `has_secure_token :api_key` fills. ## What the client receives | Request | Result | |---|---| | no `Authorization` header | 401, `WWW-Authenticate: Token realm="Webhooks Relay"`, body `HTTP Token: Access denied.` | | `Bearer` or `Token` with an unknown key | same 401, because the block returned `nil` | | valid key | the action runs; `@current_account` is set | | `Basic` credentials | same 401: the token parser ignores that scheme | The challenge names the `Token` scheme even when the client sent `Bearer`. The 401 is rendered as `text/plain`; the `message` argument changes the text, not the format. ## A JSON error instead For API clients that expect JSON, use the non-rendering variant: ```ruby def authenticate_account! @current_account = authenticate_with_http_token { |token, _| Account.find_by(api_key: token) } return if @current_account response.headers["WWW-Authenticate"] = %(Token realm="Webhooks Relay") render json: { error: "invalid_api_key" }, status: :unauthorized end ``` ## Production notes - **Lookups.** One `find_by` per request on an indexed column is the usual cost; cache nothing that would outlive a key rotation. - **Logs.** A new app's `filter_parameters` already masks names containing `token` and `_key`. - **Tests.** `ActionController::HttpAuthentication::Token.encode_credentials(account.api_key)` builds a `Token token="..."` header value for request tests. - **Shared secrets.** When the token is one fixed value rather than a per-account lookup, compare it with `ActiveSupport::SecurityUtils.secure_compare`, not `==`. ## Common misreadings - **"Only Bearer works."** `Token` headers are parsed too, and are the format `encode_credentials` produces. - **"API controllers have it already."** Only `ActionController::Base` includes the module. - **"A nil lookup just leaves the account unset."** It renders a 401 and the action never runs. - **"The block must return true."** Any truthy value passes, which is why returning the account is the idiom. ## Where the key should come from The helper only parses the header; the lookup in the block is yours. Looking the key up with `find_by` on a column filled by `has_secure_token` gives one account per key and a revocation path through `regenerate_api_key`. Whether that column should hold the raw key or a digest is a design decision this helper leaves to you, and a key that never reaches the block, because the header is missing or malformed, never touches the database at all.
- How do you return a JSON 401 instead of Rails' plain-text challenge?Call `authenticate_with_http_token`, which yields the token like its sibling but returns `nil` instead of rendering when there is no token or the block returns nothing. If the result is `nil`, set `WWW-Authenticate` yourself and `render json: { error: "invalid_api_key" }, status: :unauthorized`. Rendering from the `before_action` halts the chain.
- What does the options hash yielded to the block contain?The extra `key=value` pairs that follow the token in a `Token` header, split on commas, semicolons or tabs with quotes stripped: `Token token="abc", nonce="def"` yields `"abc"` and `{ "nonce" => "def" }` with indifferent access. A `Bearer abc` header carries none, so the hash is empty.
- authenticate_or_request_with_http_token only understands the Bearer prefix.
- ActionController::API includes the HTTP token helpers by default.
- When the block returns nil, the action still runs with no account.
- A failed token check makes Rails answer 403 Forbidden.
- The block's return value is ignored; only an exception rejects the request.