skip to content

Logins & Permissions

How a Rails app proves who a user or API client is and what they may do: generated sessions, gem sign-in, social login, OAuth tokens and policy objects. Interviewers ask which you would reach for.

part ofRuby on Railsread it →
on this pageshow

explore

questions

page 1 of 2

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

In CanCanCan, how does one Ability class let library patrons read the catalogue while librarians manage loans, and how is it checked?

level: juniorimportance: must knowfreq 60%

basics

~20 s

Every rule lives in Ability#initialize(user) as can or cannot calls: can :read, Book for everyone, can :manage, Loan for librarians. Controllers and views check with can?, and authorize! raises CanCan::AccessDenied when the rule set refuses.

open as a page

With Devise 5, what do `devise_for :users` and `before_action :authenticate_user!` give a Rails controller, and what does a signed-out visitor get back?

level: juniorimportance: must knowfreq 78%

basics

~10 s

devise_for :users registers a :user mapping with its routes and defines authenticate_user!, user_signed_in?, current_user and user_session. A signed-out HTML or Turbo visitor is redirected to the sign-in page; a JSON request gets a 401.

open as a page

With the Doorkeeper gem, what do doorkeeper:install, use_doorkeeper and resource_owner_authenticator each contribute when a Rails app becomes an OAuth 2 provider?

level: juniorimportance: must knowfreq 30%

basics

~10 s

Doorkeeper's doorkeeper:install generator writes the initializer and adds use_doorkeeper, which draws /oauth/authorize, /oauth/token and the client screens; resource_owner_authenticator is the block that returns the signed-in user or redirects to sign-in.

open as a page

In a Rails app using OmniAuth 2, how does a Sign in with GitHub click travel from the button to your callback action?

level: juniorimportance: must knowfreq 50%

basics

~20 s

OmniAuth::Builder is Rack middleware. A POST to /auth/github runs the request phase and redirects to the provider; the provider sends the browser back to /auth/github/callback, where the middleware stores the result in request.env["omniauth.auth"] and passes the request to your routed action.

open as a page

With Pundit 2.5 in a Rails forum app, how do `include Pundit::Authorization`, a `PostPolicy` and `authorize @post` decide who may edit a post?

level: juniorimportance: must knowfreq 70%

basics

~20 s

authorize @post finds PostPolicy from the record's class, builds it with pundit_user (current_user by default) and the post, and calls the predicate named after the action, such as update?. False raises Pundit::NotAuthorizedError; true returns the post.

open as a page

In an Active Record model, what does has_secure_token :api_key provide, and when does Rails 8.1 fill in the value?

level: juniorimportance: must knowfreq 45%

basics

~20 s

has_secure_token :api_key fills the api_key column with a random 24-character Base58 string and adds regenerate_api_key; under Rails 8.1 defaults the value is set when a new record is initialized, and it is stored as plain text.

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 a CanCanCan Ability, how do the order of can and cannot rules, hash conditions and blocks combine to decide a check on one record?

level: middleimportance: must knowfreq 52%

basics

~20 s

CanCanCan checks the matching rules newest first, so a later rule overrides an earlier one. Multiple can rules are alternatives, a cannot must come after the can it narrows, and a rule takes either a hash of conditions or a block, never both.

open as a page

With Devise 5, which behaviour does each of the ten model modules supply, and which five does `rails generate devise User` enable?

level: middleimportance: must knowfreq 62%

basics

~10 s

The generator enables database_authenticatable, registerable, recoverable, rememberable and validatable. Confirmable, lockable, timeoutable, trackable and omniauthable are opt-in; each module adds its own columns, routes, controller or Warden hook to the model.

open as a page

With Doorkeeper, what does before_action -> { doorkeeper_authorize! :read_workouts, :write_workouts } let through, and what does a refused request receive?

level: middleimportance: must knowfreq 28%

basics

~20 s

Doorkeeper's doorkeeper_authorize! passes a request whose access token exists, is unexpired and unrevoked, and carries at least one listed scope; a missing or dead token gets 401, a live token with none of the scopes gets 403.

open as a page

In a Rails OmniAuth callback, what does request.env['omniauth.auth'] contain, and how should the action find the local user from it?

level: middleimportance: must knowfreq 55%

basics

~20 s

It holds an OmniAuth::AuthHash with provider, uid, info (name, email and similar), credentials and extra. The action should look up a local identity by provider plus uid, behind a unique index, and treat email only as profile data.

open as a page

With Pundit, how does `policy_scope(Post)` decide which forum posts an index lists, and why use it in show as well?

level: middleimportance: must knowfreq 60%

basics

~10 s

policy_scope(Post) builds PostPolicy::Scope with pundit_user and Post and returns its resolve, usually a filtered relation. Finding the show record through that relation keeps hidden posts unreachable and turns them into a not-found error.

open as a page

In a Rails API controller, how do you authenticate each request by a per-account API key with authenticate_or_request_with_http_token?

level: middleimportance: must knowfreq 45%

basics

~10 s

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

open as a page

In a Rails controller, what does http_basic_authenticate_with name:, password: do, and when is it the right guard?

level: juniorimportance: should knowfreq 32%

basics

~20 s

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

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

With CanCanCan 3.6, what SQL does `Loan.accessible_by(current_ability)` build from the Ability's rules, and when does it raise instead?

level: middleimportance: should knowfreq 42%

basics

~20 s

accessible_by turns the hash conditions of the rules matching :index into a WHERE clause: can rules are ORed, later cannot rules add NOT ... AND, and no matching rule gives an always-false condition. A block-only rule cannot become SQL, so it raises CanCan::Error.

open as a page

What does CanCanCan's `load_and_authorize_resource` do in each action of a LoansController, and where does it surprise developers?

level: middleimportance: should knowfreq 45%

basics

~20 s

load_and_authorize_resource adds a before_action that loads @loans with accessible_by on index, finds @loan by id on member actions, builds it from strong parameters on new and create, then calls authorize! with the action name on that resource.

open as a page

With Devise 5, how do you let the sign-up form save extra fields such as company_name, and where can that code live?

level: middleimportance: should knowfreq 58%

basics

~10 s

Devise builds the user from devise_parameter_sanitizer.sanitize(:sign_up), which permits only the authentication keys, password and password_confirmation. Add fields with devise_parameter_sanitizer.permit(:sign_up, keys: [:company_name]) in a filter or in an overridden registrations controller.

open as a page

In a Rails 8.1 integration test, how do you sign in a user with Devise 5, and why might an unconfirmed user still be bounced?

level: middleimportance: should knowfreq 44%

basics

~20 s

Include Devise::Test::IntegrationHelpers and call sign_in(user) before the request; it logs the user in through Warden's test mode instead of posting the form. Devise's activation check still runs, so an unconfirmed or locked user is signed straight out.

open as a page

In Doorkeeper, how do default_scopes and optional_scopes differ, and which scopes does an access token get when the client's request names none?

level: middleimportance: should knowfreq 20%

basics

~10 s

In Doorkeeper, default_scopes are granted when a client requests no scope, while optional_scopes are granted only when named; together they are the scopes the server accepts, and a client's registered scopes narrow that set.

open as a page

With Devise 5's :omniauthable, how does OmniAuth setup in a Rails app differ from mounting OmniAuth::Builder yourself?

level: middleimportance: should knowfreq 40%

basics

~20 s

Devise builds the strategies from config.omniauth in its initializer instead of OmniAuth::Builder, scopes the paths under the model (/users/auth/github), routes the callback to an action named after the provider, and handles failures in its own controller.

open as a page

With Pundit, how does `permitted_attributes` let forum moderators set a post's pinned flag while authors may edit only title and body?

level: middleimportance: should knowfreq 38%

basics

~10 s

Define permitted_attributes in PostPolicy to return the keys the current user may write, such as adding :pinned for moderators. The controller's permitted_attributes(@post) fetches params[:post] and permits exactly those keys.

open as a page

How do you test Pundit policies and their scopes in a Rails app, with RSpec's permissions DSL or with Minitest?

level: middleimportance: should knowfreq 34%

basics

~20 s

Test policies as plain objects: build the policy with a user and a record and assert each predicate. RSpec users can require pundit/rspec for the permissions block and permit matcher; scopes are tested by calling resolve and checking which records come back.

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

As a library system's authorization rules grow, when would you keep CanCanCan's single Ability class and when move to Pundit's per-model policies?

level: seniorimportance: should knowfreq 44%

basics

~20 s

CanCanCan suits rules that fit hash conditions: one Ability answers record checks and, through accessible_by, listings. Pundit suits rules needing Ruby logic per model, at the cost of writing each predicate and its Scope separately and keeping them consistent.

open as a page

After upgrading an older app to Devise 5 on Rails 8.1 with Turbo, failed sign-ins show no errors; which Devise settings and code must change?

level: seniorimportance: should knowfreq 46%

basics

~10 s

Devise's own responder defaults are 200 for errors and 302 for redirects; only newly generated initializers set 422 and 303. Add config.responder.error_status = :unprocessable_content and redirect_status = :see_other, then replace APIs Devise 5 removed.

open as a page

In a tenant-portal app already running Devise 5, what does adding :confirmable and :lockable to User take, and what breaks for existing tenants?

level: seniorimportance: should knowfreq 42%

basics

~20 s

Add the confirmable and lockable columns in a migration, enable the modules, and backfill confirmed_at for existing users. Otherwise every current tenant is unconfirmed, and with the default 0.days grace Devise signs them out and refuses them.

open as a page

showing 1–30 of 38