Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 37 ยท Authentication and Security

Authentication with has_secure_password

Build login in Rails with has_secure_password and bcrypt, understand password hashing and salting, authenticate_by, the Rails 8 authentication generator, and password reset tokens. Includes a runnable hashing stand-in.

Authentication answers one question: who is making this request? Users prove their identity with something they know (a password), have (a phone), or are. Almost every Rails app starts with email and password, and Rails ships what you need to do that securely without a big gem: has_secure_password.

Before any code, the most important rule: never store passwords. Store a hash, a one-way scrambled form that can be checked but not reversed. If your database leaks, the attacker gets hashes that take enormous effort to crack, not passwords people reuse on other sites. This lesson shows how Rails does it, with a runnable stand-in of the hashing idea. Real Rails code is read-only because the runner has no gems or database. The next lesson, sessions and cookies, covers keeping the user logged in.

has_secure_password

Ruby
# Gemfile: gem "bcrypt", "~> 3.1"  (uncomment it in a new Rails app)
class User < ApplicationRecord
  has_secure_password
  normalizes :email, with: ->(e) { e.strip.downcase }
  validates :email, presence: true, uniqueness: true
  validates :password, length: { minimum: 12 }, allow_nil: true
end

The migration needs one column, password_digest:

SH
bin/rails generate model User email:string:uniq password_digest:string

has_secure_password adds:

  • virtual attributes password and password_confirmation (never stored, only used to compute the digest),
  • a validation that the password is present on create, at most 72 bytes (a bcrypt limit), and matches the confirmation if given,
  • authenticate(password): returns the user if the password is right, otherwise false,
  • authenticate_by(email: ..., password: ...) as a class method (Rails 7.1+).
Ruby
user = User.create!(email: "[email protected]", password: "correct horse battery")
user.password_digest         # => "$2a$12$..." (bcrypt hash with its own salt and cost)
user.authenticate("wrong")   # => false
user.authenticate("correct horse battery")   # => user

User.authenticate_by(email: "[email protected]", password: "correct horse battery")

authenticate_by is preferred for login: when the email does not exist it still spends the time of a hash comparison, so an attacker cannot learn which emails are registered by timing the response.

Why bcrypt, and what salting means

A fast hash such as SHA-256 is wrong for passwords: an attacker can try billions of guesses per second on a graphics card. Password hashes are deliberately slow and use a random salt per password, so identical passwords produce different digests and precomputed tables ("rainbow tables") are useless. bcrypt has a cost factor that doubles the work for each increment; Rails uses a lower cost in tests for speed.

The stand-in below uses PBKDF2, a similar slow, salted hash that ships with Ruby's OpenSSL, to show the shape of the idea. It is only an illustration; real apps should use bcrypt through has_secure_password (or Argon2 through a gem).

Ruby Stand-in: salted, slow password hashing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice that the same password produced two different digests: the salt is stored inside the digest string, so verify can reuse it. That is exactly how bcrypt's $2a$12$salt+hash string works.

A login flow, step by step

Ruby
# config/routes.rb
resource :session, only: %i[new create destroy]

# app/controllers/sessions_controller.rb
class SessionsController < ApplicationController
  def create
    if user = User.authenticate_by(email: params[:email], password: params[:password])
      reset_session                       # new session id after login (prevents session fixation)
      session[:user_id] = user.id
      redirect_to root_path, notice: "Signed in"
    else
      flash.now[:alert] = "Wrong email or password"   # same message for both cases
      render :new, status: :unprocessable_entity
    end
  end

  def destroy
    reset_session
    redirect_to root_path, notice: "Signed out"
  end
end

Two details: say "wrong email or password" (do not reveal which part was wrong), and call reset_session on login so an attacker cannot plant a known session id before the user signs in.

The Rails 8 authentication generator

Rails 8 can write a complete, session-based authentication system into your app:

SH
bin/rails generate authentication

It creates a User with has_secure_password, a Session model that stores one row per login (with IP address and user agent), a Current object (Current.user), SessionsController, PasswordsController with reset emails, an Authentication concern that every controller includes, and a require_authentication before-action. It is plain code in your repo, so you read it and change it; it is a good starting point and teaches you the pattern. For social logins, magic links or passkeys you add gems (OmniAuth, WebAuthn) on top, and the popular Devise gem is the other big option when you want many features at once.

Password reset tokens

A reset link must be single-use, expire quickly, and not require storing tokens by hand. Rails 7.1 added signed, expiring tokens:

Ruby
class User < ApplicationRecord
  generates_token_for :password_reset, expires_in: 15.minutes do
    password_digest.last(10)      # changes when the password changes, which invalidates the token
  end
end

token = user.generate_token_for(:password_reset)
User.find_by_token_for(:password_reset, token)   # => user, or nil if expired or used

The block ties the token to current data, so once the password changes the old token stops working. Email the link, and never reveal in the response whether an address exists ("If that address is registered, we sent a link").

Ruby Stand-in: a tamper-proof expiring token

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Common mistakes

  • Storing or logging plain passwords (also check your log filter: config.filter_parameters should include :password; Rails does by default).
  • Using == to compare secrets (use authenticate or secure_compare).
  • Allowing unlimited login attempts. Rails 7.2+ has rate_limit to: 10, within: 3.minutes, only: :create in controllers.
  • Requiring a complex mix of characters but allowing only 8 characters. Prefer length (12+) and allow passphrases.
  • Skipping HTTPS. Set config.force_ssl = true in production.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does has_secure_password store in the database?

    Only a one-way salted hash is stored; password and password_confirmation are virtual attributes.
  2. 2. Why is a slow hash such as bcrypt used instead of SHA-256 for passwords?

    A deliberately expensive hash makes offline cracking far more costly.
  3. 3. Why call reset_session when a user logs in?

    A new session id means an id planted before login cannot be used afterward.
  4. 4. What is the advantage of User.authenticate_by(email:, password:)?

    It hashes even when no user is found, so response time does not leak which emails are registered.

Summary

  • Store only a slow, salted hash; has_secure_password gives password_digest, authenticate and authenticate_by.
  • Use one error message for wrong email or wrong password and call reset_session on login.
  • bin/rails generate authentication (Rails 8) writes a full session-based system you own.
  • generates_token_for makes signed, expiring, single-use reset tokens.
  • Add rate limiting, HTTPS and long passwords.

Next: Sessions and cookies