In Active Record with has_secure_password, why does the Rails 8 sessions controller call User.authenticate_by rather than find_by(...)&.authenticate?
answer
- nil, never false
- hashes even when no row matches
- timing-based account enumeration
- blank password: no query at all
- ArgumentError without both kinds
basics
~20 sauthenticate_by looks the user up and checks the password in one call, returns the record or nil, and runs the bcrypt comparison even when no user matches, so response time does not reveal which email addresses have accounts.
solid answer
~40 s`User.authenticate_by(email_address:, password:)` splits its hash into password attributes (those backed by a `*_digest` column) and finder attributes, runs `find_by` on the finders, then calls `authenticate_password` on the result. If no record matches it still builds `new(password: ...)`, which hashes the password with bcrypt, so a miss costs about as long as a wrong password. That closes the timing side channel that `find_by(email_address: e)&.authenticate(p)` opens: a missing user returns in microseconds, a wrong password after a deliberately slow bcrypt check. It also returns `nil` on every failure, where `authenticate` returns `false`, returns `nil` without a query for a blank password, and raises `ArgumentError` if either kind of attribute is missing. It exists since Rails 7.1.
code
ruby · 7 linesUser.authenticate_by(email_address: "[email protected]", password: "right") # => #<User ...>
User.authenticate_by(email_address: "[email protected]", password: "wrong") # => nil
User.authenticate_by(email_address: "[email protected]", password: "x") # => nil, still hashes
User.authenticate_by(email_address: "[email protected]", password: "") # => nil, no query
User.authenticate_by(email_address: "[email protected]") # ArgumentError
User.find_by(email_address: "[email protected]")&.authenticate("wrong") # => falsego deeper
Know that authenticate returns the user or false, and that authenticate_by finds and checks in one call, returning the user or nil.
Explain the partition into finder and password attributes, the ArgumentError, the no-query path for a blank password, and the dummy hash on a miss.
Explain why identical error text still leaks account existence through timing, and use extra finders like active: true rather than post-checks.
Place the timing defence alongside rate limiting and messaging as one enumeration posture, and decide which layer of the stack owns each part.
## The two methods `has_secure_password` gives a model two ways to check a password: - **`user.authenticate(password)`** (an alias of `authenticate_password`) is an **instance** method. It returns the record when the password matches the stored `password_digest`, and **`false`** otherwise. - **`User.authenticate_by(attributes)`** is a **class** method added to Active Record in **Rails 7.1**. It finds and authenticates in one step and returns the record or **`nil`**. The generated `SessionsController#create` in Rails 8 uses the second: ```ruby if user = User.authenticate_by(params.permit(:email_address, :password)) start_new_session_for user redirect_to after_authentication_url else redirect_to new_session_path, alert: "Try another email address or password." end ``` ## What authenticate_by does, step by step 1. It converts its argument with `to_h`. An `ActionController::Parameters` object must therefore be permitted first, or `to_h` raises `ActionController::UnfilteredParameters`; that is why the generated code calls `params.permit`. 2. It **partitions** the pairs: a key is a password attribute when the model has no column by that name but has a `<name>_digest` column. Everything else is a finder. 3. It raises **`ArgumentError`** if there is no password attribute, or no finder attribute. 4. If any password value is `nil` or empty, it returns **`nil` without querying**. 5. It runs `find_by(identifiers)`. If a record is found, it returns it only when every password attribute authenticates. 6. If **no record** is found, it calls `new(passwords)` and returns `nil`. Assigning the password to a new instance runs `BCrypt::Password.create`, which costs about as much as a real comparison. ## Why step 6 matters bcrypt is deliberately slow. With `find_by(...)&.authenticate(...)`: | Case | Work done | Typical time | |---|---|---| | Unknown email | one indexed query, no hashing | very short | | Known email, wrong password | query plus a bcrypt check | noticeably longer | | Known email, right password | query plus a bcrypt check | noticeably longer | An attacker timing the sign-in form can tell the first row from the other two and so learn which addresses have accounts, even though the page shows the same message. `authenticate_by` makes the miss pay for a hash too, so all three cases take roughly the same time. The policy reasons for hiding account existence belong to credential-recovery design; the Rails mechanism is this extra hash. ## Return values and gotchas - **`nil`, not `false`**, on every failure, so the result can be used directly in `if user = ...`. - **Finder normalisation applies.** The generated `User` declares `normalizes :email_address, with: ->(e) { e.strip.downcase }`, and normalisation also applies to the `where` that `find_by` builds, so `" [email protected] "` finds the same row. - **Extra finders narrow the match.** Any non-password attribute becomes part of `find_by`, so `User.authenticate_by(email_address: e, password: p, active: true)` refuses deactivated accounts in the same call. - **bcrypt's 72-byte limit.** `has_secure_password` adds a validation that a new password is at most 72 bytes, because bcrypt ignores what follows; the generated sign-in form also sets `maxlength: 72`. - **Rate limiting is separate.** The generated controller adds `rate_limit to: 10, within: 3.minutes, only: :create`, keyed by client IP; `authenticate_by` itself does not count failures. ## More than one password attribute A model can declare `has_secure_password` more than once, for example `has_secure_password :recovery_password, validations: false`, which needs a `recovery_password_digest` column and defines `authenticate_recovery_password`. `authenticate_by` treats every key backed by a digest column as a password, and returns the record only when **all** of them authenticate, so `User.authenticate_by(email_address: e, password: p, recovery_password: r)` demands both secrets. ## When you still use authenticate `authenticate` remains right when you already hold the record and want to re-check a password, for example confirming the current password before a sensitive change. For a password change itself, `has_secure_password` also offers a `password_challenge` attribute that validates against the persisted digest on save.
- How would you stop a deactivated clerk signing in without changing the controller's shape?Pass the flag as another finder: `User.authenticate_by(email_address: e, password: p, active: true)`. Every non-password attribute goes into `find_by`, so an inactive account is treated like an unknown one, including the dummy hash on a miss.
- Why does the generated controller pass params.permit(...) rather than params directly?`authenticate_by` calls `to_h` on its argument, and `ActionController::Parameters#to_h` raises `ActionController::UnfilteredParameters` unless the parameters are permitted. Permitting only `:email_address` and `:password` also keeps any other submitted key out of the `find_by`.
- authenticate_by returns false for a wrong password, like authenticate.
- find_by(...)&.authenticate is just as safe because the error message is identical.
- authenticate_by skips hashing when the email is unknown, to save time.
- authenticate_by accepts a password alone and finds the user by digest.
- has_secure_token is what authenticate_by checks the password against.
Assumes Rails 8.1; authenticate_by exists since Rails 7.1, so apps on older releases only have find_by followed by authenticate.