skip to content

Devise

The most widely used Rails authentication gem, assembled from modules such as registerable, confirmable, recoverable and lockable on top of Warden. Interviewers probe what each module actually adds.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

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%

answer

  1. one mapping, four generated helpers
  2. warden.authenticate! with scope: :user
  3. throw :warden, caught by Warden::Manager
  4. navigational formats redirect, others 401
  5. current_user memoised, nil when signed out

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.

solid answer

~30 s

`devise_for :users` in config/routes.rb creates a `:user` mapping, draws the routes for the model's modules and generates four helpers: `authenticate_user!`, `user_signed_in?`, `current_user` and `user_session`. `authenticate_user!` calls `warden.authenticate!(scope: :user)`; when no strategy succeeds Warden does `throw :warden`, the `Warden::Manager` middleware catches it and hands the request to `Devise::FailureApp`. For navigational formats (`*/*`, `:html`, `:turbo_stream`) the failure app stores the attempted GET path, sets a flash alert and redirects to `new_user_session_path`; for JSON or XHR it answers 401 with an error body. The action never runs. `current_user` returns the signed-in record (memoised per request) or `nil`.

code

ruby · 20 lines
ruby
# config/routes.rb
Rails.application.routes.draw do
  devise_for :users
  resources :invoices
  root "pages#home"
end

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :authenticate_user!
end

# app/controllers/pages_controller.rb
class PagesController < ApplicationController
  skip_before_action :authenticate_user!, only: :home

  def home
    @greeting = user_signed_in? ? "Hi #{current_user.email}" : "Welcome"
  end
end

go deeper

for a junior

Know the four helpers devise_for generates, put authenticate_user! in a before_action, and expect current_user to be nil for guests.

for a middle

Explain the path from warden.authenticate! through throw :warden to Devise::FailureApp, and why HTML is redirected while JSON gets a 401.

for a senior

Show you can bend the failure behaviour safely: navigational formats, http_authenticatable_on_xhr, a FailureApp subclass, and stored locations for deep links.

for a principal

Weigh a global authenticate filter with explicit public exceptions against per-controller opt-in, and how each fails when a new controller is added.

## What `devise_for` sets up **Devise** is an authentication gem built on **Warden**, a Rack-level authentication framework. Two pieces connect them to a Rails app: - The Devise engine adds the `Warden::Manager` middleware to the app's middleware stack. On every request it puts a `Warden::Proxy` object into the Rack env under `env['warden']`; that proxy is what `warden` returns inside a controller. The middleware does **not** authenticate anything by itself; it only provides the proxy and catches failures. - `devise_for :users` in `config/routes.rb` creates a **mapping** named `:user` (the singular of the resource), points it at the `User` model, and draws routes for every module the model enables (`/users/sign_in`, `/users/password/new` and so on). For each mapping Devise generates controller helpers, also exposed to views through `helper_method`: | Helper | What it does | |---|---| | `authenticate_user!` | Calls `warden.authenticate!(scope: :user)`; halts the request when no user can be authenticated | | `user_signed_in?` | `true` when `current_user` is present | | `current_user` | `@current_user ||= warden.authenticate(scope: :user)`, the record or `nil` | | `user_session` | A per-scope slice of the session, only while a user is signed in | A second mapping (`devise_for :admins`) produces `authenticate_admin!`, `current_admin` and so on. Each scope signs in independently. ## What happens when `authenticate_user!` fails `authenticate_user!` is meant to be used as a filter: `before_action :authenticate_user!`. When the visitor is signed out, the sequence is: 1. `warden.authenticate!` runs the scope's strategies (for example the remember-me cookie). None succeeds. 2. Warden executes `throw :warden` with the scope in its options. The controller action never runs; with no strategy message, the failure app later falls back to `:unauthenticated`. 3. `Warden::Manager#call` catches the throw and calls its failure app. Devise configures that as `Devise::Delegator`, which picks the mapping's failure app, `Devise::FailureApp` unless you set another. 4. `Devise::FailureApp#respond` chooses one of three answers: - **redirect** for navigational formats: it stores the attempted path in the session (GET requests only), sets `flash[:alert]` from the `devise.failure` locale keys, and redirects to `new_user_session_url`; - **http_auth** for non-navigational formats such as JSON, and for XHR requests while `http_authenticatable_on_xhr` is `true` (its default): status 401 and a body like `{"error":"You need to sign in or sign up before continuing."}`; - **recall** when the failing call carried a `recall:` option, which is how a wrong password on the sign-in form re-renders `sessions#new` instead of redirecting. `Devise.navigational_formats` defaults to `["*/*", :html, :turbo_stream]`, so browser and Turbo requests are redirected while API clients get a 401. ## Why the sign-in page does not loop A common setup puts the filter in `ApplicationController` so every page requires a login. Devise's own controllers inherit from `Devise.parent_controller`, which defaults to `"ApplicationController"`, so they inherit that filter too. They still work because the generated `authenticate_user!` only calls Warden when `devise_controller?` is false, unless you pass `force: true`. Public pages in your own app opt out with `skip_before_action :authenticate_user!`. ## After sign-in: back to where the visitor was going Because the failure app stored the attempted GET path, `after_sign_in_path_for` first returns `stored_location_for(resource)` and otherwise falls back to `user_root_path` or `root_path`. Override `after_sign_in_path_for` in `ApplicationController` to change that. ## Guards in the router instead of the controller Devise also adds route-level helpers to `config/routes.rb`, useful when a whole block of routes, or a mounted engine, must be protected: - `authenticate :user do ... end` runs `warden.authenticate!` as a routing constraint, so a signed-out visitor goes through the same failure app; - `authenticated :user do ... end` only matches when a user is signed in, which lets two `root` routes coexist (a dashboard for members, a landing page for guests); - both accept a lambda for extra checks on the record, such as `->(u) { u.admin? }`. These guard routing only; controllers reached by other routes still need their own filter. ## Common mistakes - Expecting `current_user` to raise when nobody is signed in: it returns `nil`, so `current_user.name` in a public view raises `NoMethodError` instead. - Calling `current_user` in a controller with no `authenticate_user!` filter and assuming the action is protected. - Expecting a JSON client to follow a 302 to an HTML sign-in form; it receives a 401. - Seeing `Devise::MissingWarden`: it means `env['warden']` is absent, usually a test that skips the middleware stack, not a signed-out user.

  • Why doesn't a global before_action :authenticate_user! lock visitors out of the Devise sign-in page itself?
    Devise controllers inherit from `Devise.parent_controller`, by default `ApplicationController`, so they do inherit the filter. The generated `authenticate_user!` only calls `warden.authenticate!` when `devise_controller?` is false (or when you pass `force: true`), so on `Devise::SessionsController` it does nothing and the form renders.
  • A fetch() call from a Stimulus controller gets a 302 to the sign-in page instead of a 401; why, and how do you change it?
    The failure app answers 401 only for non-navigational formats or for XHR requests. A plain `fetch` sends `Accept: */*` and no `X-Requested-With` header, and `*/*` is in `Devise.navigational_formats`, so it is redirected. Send `Accept: application/json`, or subclass `Devise::FailureApp` and install it with `config.warden { |manager| manager.failure_app = MyFailureApp }`.
  • How does Devise send a visitor back to the page they asked for after signing in?
    On a GET redirect the failure app calls `store_location_for(scope, attempted_path)`, which keeps the path in the session. After a successful sign-in, `after_sign_in_path_for` returns `stored_location_for(resource)` first and falls back to `user_root_path` or `root_path`.

  • authenticate_user! returns false and the action still renders for guests
  • current_user raises an exception when nobody is signed in
  • Devise's middleware blocks every unauthenticated request before routing, so filters are optional
  • A JSON client receives the same 302 to the sign-in form as a browser
  • Devise controllers do not inherit from ApplicationController
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 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

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