In a Rails controller, what does http_basic_authenticate_with name:, password: do, and when is it the right guard?
answer
- a class macro adding a before_action
- only: and except: pass through
- secure_compare on name and password
- 401 with WWW-Authenticate: Basic realm
- nil from ENV raises ArgumentError
basics
~20 shttp_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.
solid answer
~40 s`http_basic_authenticate_with name: "ops", password: Rails.application.credentials.ops_password, except: :index` adds a `before_action`, passing through options such as `only:` and `except:`, that decodes the `Authorization: Basic` header and compares both values with `ActiveSupport::SecurityUtils.secure_compare`, joined with `&` so a wrong name does not skip the password check. A mismatch or missing header answers 401 with `WWW-Authenticate: Basic realm="Application"` and `HTTP Basic: Access denied.`; `realm:` changes the realm. It checks one shared credential, so it fits a staging site, a small admin dashboard or a metrics page, not per-user sign-in. Both values must be Strings: a missing environment variable or credential passes `nil`, and the macro raises `ArgumentError` when the controller class loads. For a per-account check, call `authenticate_or_request_with_http_basic` with a block.
code
ruby · 14 linesclass Admin::DeliveriesController < ApplicationController
http_basic_authenticate_with name: "ops",
password: Rails.application.credentials.ops_password!,
realm: "Relay Admin",
except: :health
def index
@deliveries = Delivery.order(created_at: :desc).limit(100)
end
def health
head :ok
end
endgo deeper
Recall that the macro adds a before_action with one fixed name and password, takes only: and except:, and answers 401 with a Basic challenge.
Explain the secure_compare check, the String requirement that turns a missing ENV value into ArgumentError, and when authenticate_or_request_with_http_basic with a block fits better.
Show judgement about where one shared credential is acceptable, such as staging or a metrics page, keeping it in credentials and testing the 401 path.
Decide which internal surfaces may rely on a shared credential and which need per-person sign-in and audit trails, and how shared secrets rotate when people leave.
## What the macro is `http_basic_authenticate_with` is a **class macro** from `ActionController::HttpAuthentication::Basic::ControllerMethods`, which `ActionController::Base` includes. It guards a controller with one fixed name and password sent through the browser's built-in Basic prompt: ```ruby class Admin::DeliveriesController < ApplicationController http_basic_authenticate_with name: "ops", password: Rails.application.credentials.ops_password!, realm: "Relay Admin", except: :health end ``` ## What it does, step by step 1. It raises `ArgumentError` right away unless `name:` and `password:` are both Strings. 2. It calls `before_action(options)` with a block, so `only:`, `except:`, `if:` and `unless:` apply as on any filter. 3. On each request the block decodes the `Authorization: Basic` header into a name and password. 4. It compares both with `ActiveSupport::SecurityUtils.secure_compare`, combined with `&` rather than `&&`, so both comparisons always run. 5. On a mismatch, or with no Basic header, it sets `WWW-Authenticate: Basic realm="..."`, status 401 and the body `HTTP Basic: Access denied.`, which halts the callback chain. ## The method family | Method | Use | |---|---| | `http_basic_authenticate_with name:, password:, realm: nil, **options` | class macro: one fixed credential | | `http_basic_authenticate_or_request_with(name:, password:, realm: nil, message: nil)` | the same check, called from your own code | | `authenticate_or_request_with_http_basic(realm = nil, message = nil) { \|name, password\| ... }` | your block decides; falsy renders the 401 | | `authenticate_with_http_basic { \|name, password\| ... }` | your block decides; returns `nil` without responding | | `request_http_basic_authentication(realm = "Application", message = nil)` | renders the 401 challenge only | `ActionController::API` does not include the module; an API controller adds `include ActionController::HttpAuthentication::Basic::ControllerMethods` first. ## When it is the right guard - A **staging or preview site** that must not be public. - A **small internal page** a few operators open, such as a delivery-queue dashboard. - A **metrics or status endpoint** scraped by a tool that can send Basic credentials. It is the wrong guard for anything per person: everyone shares one password, nobody's actions are attributed, and changing the password locks everyone out at once. Per-account checks use `authenticate_or_request_with_http_basic` with a block that looks the account up, or the token helpers. ## The nil trap ```ruby http_basic_authenticate_with name: ENV["OPS_USER"], password: ENV["OPS_PASS"] ``` On a server where `OPS_PASS` is unset, `ENV["OPS_PASS"]` is `nil`, and the macro raises `ArgumentError: Expected password: to be a String, got NilClass` when the class body runs: at boot with eager loading, on first use without it. That is deliberate, failing loudly instead of comparing against `nil`. `Rails.application.credentials.ops_password` returns `nil` for a missing key in the same way; the bang form, `credentials.ops_password!`, raises `KeyError` with the key's name, which is easier to diagnose. ## Exempting an action Because the filter is a block, `skip_before_action` in a subclass cannot name it. Use `except:` or `only:` on the macro itself, for example `except: :health` for a load-balancer check. ## Testing `ActionController::HttpAuthentication::Basic.encode_credentials("ops", password)` builds the header value for a request test; expect `:unauthorized` without it. ## Basic or token? | Need | Rails tool | |---|---| | one shared credential for a page or a site | `http_basic_authenticate_with` | | per-account credentials a browser can prompt for | `authenticate_or_request_with_http_basic` with a block | | per-account API keys sent by servers | `authenticate_or_request_with_http_token` with a block | ## Common misreadings - **"It protects the whole app."** It guards the controller that declares it, plus subclasses, and only the actions `only:` and `except:` leave in. - **"Failure is a 403."** It is a 401 with a `WWW-Authenticate: Basic` challenge, which is what makes the browser prompt. - **"It logs the visitor in."** Nothing is stored; the browser simply resends the Basic header with each request. - **"A missing secret just disables it."** A `nil` value raises `ArgumentError` instead.
- How do you check Basic credentials against Account rows instead of one fixed pair?Call `authenticate_or_request_with_http_basic("Webhooks Relay") { |name, password| ... }` from a `before_action`. The block receives the decoded name and password; return the account when they check out and `nil` or `false` otherwise, and Rails renders the 401 challenge for you. `http_basic_authenticate_with` cannot do this, since it only accepts String values.
- How do you leave one action open, such as a health check?Pass `except: :health` (or `only:`) to the macro, since its options go straight to `before_action`. A subclass cannot use `skip_before_action` for it, because the macro registers an anonymous block rather than a named method.
- http_basic_authenticate_with in one controller protects every controller in the app.
- A failed Basic check from the macro answers 403 Forbidden.
- http_basic_authenticate_with takes a lambda so each account can have its own password.
- Passing an ENV value that turns out nil just switches the check off.
- The macro signs the visitor in and keeps them in the session.