skip to content

Built-In Generator

Rails generates its own authentication: User and Session models, a Current object, has_secure_password and password resets, but no sign-up. Interviewers ask whether that removes the case for a gem.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In Rails 8, what does bin/rails generate authentication add to an app, and what does it deliberately leave out?

level: juniorimportance: must knowfreq 65%

answer

  1. three models, two controllers
  2. a concern injected into ApplicationController
  3. resource :session and resources :passwords
  4. bcrypt uncommented or bundle-added
  5. nothing creates a User

basics

~10 s

It writes User, Session and Current models, SessionsController, PasswordsController, an Authentication concern included in ApplicationController, a reset mailer, migrations, routes, tests and bcrypt. It creates no sign-up: no generated action makes a new User.

solid answer

~40 s

Running `bin/rails generate authentication` (Rails 8.0 and later) writes a `User` model with `has_secure_password` and `has_many :sessions`, a `Session` model whose rows record `ip_address` and `user_agent`, and a `Current` class holding the active session. It adds `SessionsController` for sign-in and sign-out, `PasswordsController` plus `PasswordsMailer` for resets, and an `Authentication` concern it injects into `ApplicationController`, so every action requires a login until a controller opts out. It also adds the routes `resource :session` and `resources :passwords, param: :token`, two migrations, ERB views, Minitest files, and enables the `bcrypt` gem. What it leaves out is sign-up: no controller or route creates a `User`, so you build registration yourself or create accounts from the console. Email confirmation, per-account lockout and session expiry are also absent.

code

bash · 2 lines
bash
bin/rails generate authentication
bin/rails db:migrate

go deeper

for a junior

Name the three models, the two controllers, the Authentication concern and the two routes, and say clearly that nothing in the output signs a new user up.

for a middle

Explain how the injected concern makes every action require a login, how allow_unauthenticated_access opts out, and what the two migrations create.

for a senior

Treat the output as code you now own: list the gaps (sign-up, confirmation, per-account lockout, expiry) and know that 8.1's template changes never reach an app generated on 8.0.

for a principal

Weigh owning a small, readable authentication layer against a maintained gem, given which of the missing features the product will actually need.

## What the command is Rails 8.0 introduced an **authentication generator**: `bin/rails generate authentication`. The 8.0 release notes call it "a starting point for a session-based, password-resettable, metadata-tracking authentication system". It is not a gem and not a runtime library: it writes ordinary application code into your project once, and from then on that code is yours to read, change and maintain. Picture an internal **stock-room tool** where a handful of clerks record deliveries and withdrawals. The tool needs sign-in, sign-out and a way to recover a forgotten password, but accounts are created by an administrator, not by strangers on the internet. That is exactly the shape the generator targets. ## The files it writes | File | Role | |---|---| | `app/models/user.rb` | `has_secure_password`, `has_many :sessions, dependent: :destroy`, `normalizes :email_address` (strip and downcase) | | `app/models/session.rb` | `belongs_to :user`; one row per signed-in browser | | `app/models/current.rb` | `Current < ActiveSupport::CurrentAttributes` with `attribute :session` and `Current.user` delegated to it | | `app/controllers/concerns/authentication.rb` | `before_action :require_authentication`, `allow_unauthenticated_access`, `start_new_session_for`, `terminate_session` | | `app/controllers/sessions_controller.rb` | `new`, `create` (via `User.authenticate_by`) and `destroy` | | `app/controllers/passwords_controller.rb` | request a reset, follow the emailed link, set a new password | | `app/mailers/passwords_mailer.rb` + `reset` views | the email carrying the reset link (only when Action Mailer is loaded) | | `app/channels/application_cable/connection.rb` | identifies Action Cable connections by the same cookie (only when Action Cable is loaded) | | `app/views/sessions/new.html.erb`, `app/views/passwords/{new,edit}.html.erb` | the sign-in and reset forms (skipped with `--api`) | The Minitest hook adds `test/fixtures/users.yml`, `test/models/user_test.rb`, controller tests for sessions and passwords, a mailer preview and `test/test_helpers/session_test_helper.rb`. ## What it changes in files you already have 1. It injects `include Authentication` into `ApplicationController`, so **every controller now requires a signed-in user** until it calls `allow_unauthenticated_access`. 2. It adds two routes: `resource :session` (singular, so `/session/new`, `POST /session`, `DELETE /session`) and `resources :passwords, param: :token`. 3. It enables **bcrypt**: a new app's Gemfile carries `# gem "bcrypt", "~> 3.1.7"` commented out, and the generator uncomments it (or runs `bundle add bcrypt` if the line is missing). 4. It generates two migrations: `users` with a unique, non-null `email_address` and a non-null `password_digest`, and `sessions` with `user` references, `ip_address` and `user_agent`. After `bin/rails db:migrate`, the app has a working sign-in page at `/session/new`. ## What it deliberately leaves out - **Sign-up.** The Security guide says it plainly: no generated code creates new `User` records. You add a registration controller, or seed accounts from the console. - **Email confirmation.** Nothing verifies that an address belongs to the person who typed it. - **Per-account lockout.** The generated `rate_limit` on `SessionsController#create` and `PasswordsController#create` counts requests per client IP (10 within 3 minutes), not failed attempts per account. - **Session expiry.** The cookie is permanent and the `Session` row has no expiry column, so a session lasts until it is destroyed. - **Password rules.** `has_secure_password` validates presence, confirmation and bcrypt's 72-byte maximum; there is no minimum length or strength check. - **Authorization.** It answers "who is this?", never "may they do this?"; roles and policies are a separate layer. ## The tests it writes The Minitest output is worth reading as documentation of the behaviour: - `test/fixtures/users.yml` sets each fixture's `password_digest` with `BCrypt::Password.create("password")`. In the test environment Active Model uses bcrypt's minimum cost, so fixtures and sign-ins stay fast. - `PasswordsControllerTest` asserts that an unknown address gets the same redirect and notice as a known one but no enqueued email, and that an invalid token redirects back to `new_password_path`. - `SessionTestHelper#sign_in_as(user)` lets any integration test start signed in without posting the form. ## Version notes The generator is a Rails **8.0** feature. Rails **8.1** changed its output: it now rate-limits the password-reset request, writes `SessionTestHelper` with `sign_in_as(user)` and `sign_out` for integration tests, generates sessions controller tests, and skips mailer files in apps without Action Mailer. Because the generator writes code once, an app generated on 8.0 keeps the 8.0 output after upgrading; the 8.1 additions arrive only if you add them by hand.

  • Since the generator ships no sign-up, how would you add one?
    Add a controller that calls `allow_unauthenticated_access`, builds `User.new(params.expect(user: [:email_address, :password, :password_confirmation]))`, and on a successful `save` calls the concern's `start_new_session_for(@user)` and redirects to `after_authentication_url`; on failure it re-renders with `status: :unprocessable_content`. Add a route and a form. The generated `User` has only a unique index on `email_address`, so add `validates :email_address, uniqueness: true` for a friendly error instead of `ActiveRecord::RecordNotUnique`.
  • What does the generator's --api option change?
    It skips the ERB view templates (`sessions/new`, `passwords/new`, `passwords/edit`). The models, concern, controllers, mailer and migrations still come from the same templates, so an API-only app still gets redirect-based actions and a signed cookie session that you then adapt to its clients.

  • The generator includes a sign-up page that you only need to route.
  • It stores the user id in session[:user_id] like a hand-rolled login.
  • Running it installs Devise and configures devise_for :users.
  • There is no sessions table; the session lives only in the cookie.
  • Upgrading Rails updates the generated controllers with the new template.

Assumes Rails 8.1.4; the generator arrived in 8.0, and 8.1 added the reset-request rate limit, SessionTestHelper and the sessions controller tests to its output.

open as a page

With Rails 8's generated authentication, how is a request recognised as signed in, from the cookie to the Session row to Current.user?

level: middleimportance: must knowfreq 55%

basics

~20 s

Sign-in creates a Session row and stores its id in a signed, permanent, httponly cookie. On each request the concern's before_action reads that cookie, loads the row into Current.session, and redirects to the sign-in page when no row matches.

open as a page

In Active Record with has_secure_password, why does the Rails 8 sessions controller call User.authenticate_by rather than find_by(...)&.authenticate?

level: middleimportance: should knowfreq 45%

basics

~20 s

authenticate_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.

open as a page

In Rails 8.1, how does has_secure_password's password_reset_token work without a token column, and what makes a reset link stop working?

level: middleimportance: should knowfreq 45%

basics

~20 s

password_reset_token is a signed, expiring message carrying the user's id and part of the password's bcrypt salt. It stops working after 15 minutes by default, or as soon as the password changes, because the salt it embedded no longer matches.

open as a page

On Rails 8's generated authentication, how do you cut a dismissed stock-room clerk off immediately, and which generated paths would still let them in?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Destroy the clerk's Session rows with user.sessions.destroy_all, disconnect their open Action Cable sockets, and block the account at sign-in and reset, because a still-valid reset email lets them set a password and sign in again.

open as a page

Rails 8 now generates its own authentication — for a stock-room tool that keeps growing, when would you keep the generated code and when adopt Devise?

level: principalimportance: should knowfreq 35%

basics

~20 s

Keep the generated code while needs stay close to sign-in, sign-out and reset, because it is small and visible. Adopt Devise when registration, confirmation, lockout, timeouts or several user types pile up and you would otherwise maintain them all.

open as a page