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?
answer
- one mapping, four generated helpers
- warden.authenticate! with scope: :user
- throw :warden, caught by Warden::Manager
- navigational formats redirect, others 401
- current_user memoised, nil when signed out
basics
~10 sdevise_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# 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
endgo deeper
Know the four helpers devise_for generates, put authenticate_user! in a before_action, and expect current_user to be nil for guests.
Explain the path from warden.authenticate! through throw :warden to Devise::FailureApp, and why HTML is redirected while JSON gets a 401.
Show you can bend the failure behaviour safely: navigational formats, http_authenticatable_on_xhr, a FailureApp subclass, and stored locations for deep links.
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