With Rails 8's generated authentication, how is a request recognised as signed in, from the cookie to the Session row to Current.user?
answer
- a row per signed-in browser
- cookies.signed.permanent[:session_id]
- require_authentication then resume_session
- Current.session ||= find_session_by_cookie
- terminate_session destroys the row
basics
~20 sSign-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.
solid answer
~30 sIn the generated `Authentication` concern, `start_new_session_for(user)` creates `user.sessions.create!(user_agent:, ip_address:)`, sets `Current.session`, and writes `cookies.signed.permanent[:session_id]` with `httponly: true, same_site: :lax`. Every controller runs `before_action :require_authentication`, which calls `resume_session`: `Current.session ||= Session.find_by(id: cookies.signed[:session_id])`. If no row is found, `request_authentication` saves the requested URL in `session[:return_to_after_authenticating]` and redirects to `new_session_path`; after sign-in, `after_authentication_url` sends the user back. `Current.user` is delegated to the session. Signing out calls `terminate_session`, which destroys the row and deletes the cookie. The signature stops a client forging another id, and because the row is the authority, deleting it revokes that browser.
code
ruby · 12 lines# app/controllers/concerns/authentication.rb (generated, excerpt)
def start_new_session_for(user)
user.sessions.create!(user_agent: request.user_agent, ip_address: request.remote_ip).tap do |session|
Current.session = session
cookies.signed.permanent[:session_id] = { value: session.id, httponly: true, same_site: :lax }
end
end
def terminate_session
Current.session.destroy
cookies.delete(:session_id)
endgo deeper
Recall that sign-in writes a Session row plus a signed session_id cookie, and that Current.user is how controllers and views reach the signed-in user.
Walk through require_authentication, resume_session and find_session_by_cookie, the return-to URL, and why Current.user is nil on actions that skip the filter.
Explain why the database row, not the cookie, is the authority, and what that buys you: revoking one browser or all of a user's browsers with a DELETE.
Judge the cost of a database lookup per request against the revocation it buys, and where an idle or absolute limit would have to be added to this code.
## Two stores, two jobs Rails 8's authentication generator keeps a signed-in browser in **two places**, and each has one job: - A **`Session` row** in the database (`sessions` table: `user_id`, `ip_address`, `user_agent`, timestamps). The row is the **authority**: while it exists, the browser is signed in. - A **signed cookie** named `session_id` holding that row's primary key. The cookie is only a **pointer**. Signing (an HMAC keyed from the app's secret) means a client cannot change the id to someone else's without the signature failing; it does not hide the value. This is not Rails' built-in `session` hash. The generated code still uses `session` for one thing, the return-to URL, but the login itself lives in its own cookie and its own table. ## Signing in `SessionsController#create` calls `User.authenticate_by(params.permit(:email_address, :password))`. On success it calls the concern's private `start_new_session_for(user)`: 1. `user.sessions.create!(user_agent: request.user_agent, ip_address: request.remote_ip)` writes a fresh row. 2. `Current.session = session` makes it available for the rest of this request. 3. `cookies.signed.permanent[:session_id] = { value: session.id, httponly: true, same_site: :lax }` sets the pointer. `permanent` sets an expiry 20 years ahead; `httponly` keeps it from JavaScript; `same_site: :lax` keeps it off most cross-site subrequests. Then the controller redirects to `after_authentication_url`, which returns the stored `session[:return_to_after_authenticating]` (deleting it) or `root_url`. ## Every later request `include Authentication` registers `before_action :require_authentication` on every controller: ```ruby def require_authentication resume_session || request_authentication end def resume_session Current.session ||= find_session_by_cookie end def find_session_by_cookie Session.find_by(id: cookies.signed[:session_id]) if cookies.signed[:session_id] end ``` - A missing, unsigned or tampered cookie reads as `nil`, so no query runs. - A valid cookie whose row was deleted finds nothing, so the user is sent to sign in. - `request_authentication` stores `request.url` and redirects to `new_session_path`. - `Current.user` comes from `delegate :user, to: :session, allow_nil: true` in `app/models/current.rb`. `Current` attributes are reset between requests, so nothing leaks from one request into the next. ## Opting out, and the trap that comes with it `allow_unauthenticated_access(**options)` is a class method that calls `skip_before_action :require_authentication, **options`. `SessionsController` uses it for `new` and `create`; `PasswordsController` for everything. The trap: on a skipped action, **`resume_session` never ran**, so `Current.user` is `nil` even for a signed-in visitor. The concern's `authenticated?` helper (exposed with `helper_method`) calls `resume_session`, so a layout that checks `authenticated?` populates `Current.session` as a side effect. Code that reads `Current.user` directly on a public page must call `resume_session` (or `authenticated?`) first. ## Signing out and revoking | Action | Generated code | Effect | |---|---|---| | Sign out | `terminate_session` | `Current.session.destroy` and `cookies.delete(:session_id)` | | Password reset completed | `@user.sessions.destroy_all` in `PasswordsController#update` | every browser of that user is signed out | | User deleted | `has_many :sessions, dependent: :destroy` | rows go with the user | Because the row is the authority, revocation is a `DELETE` in the database: the next request with the old cookie finds no row. A design that only signs the user id into a cookie cannot do that without extra state. ## Why rows rather than a signed user id | Design | Revoke one browser | List a user's devices | Cost per request | |---|---|---|---| | Signed user id in a cookie | not without extra server state | no | no query | | Generated: signed pointer to a `Session` row | destroy the row | yes, from `ip_address` and `user_agent` | one primary-key lookup | The generator chose the second: one indexed lookup per request buys revocation and a per-device audit trail, which is why `PasswordsController#update` can sign a user out everywhere with a single `destroy_all`. ## Action Cable shares the cookie When Action Cable is loaded, the generator also writes `ApplicationCable::Connection`, which runs `Session.find_by(id: cookies.signed[:session_id])` in `connect` and calls `reject_unauthorized_connection` when nothing matches. It checks once, at connect time.
- Why does the generated sign-out redirect with status: :see_other?`SessionsController#destroy` answers a `DELETE` request. A 303 makes a fetch-based client such as Turbo follow the redirect with a `GET`. With a 302, fetch rewrites only `POST` to `GET` and keeps other methods, so the follow-up would be a `DELETE` to `/session/new`, which has no route.
- How does the generated SessionTestHelper sign a user in for an integration test?`sign_in_as(user)` creates `user.sessions.create!`, stores it in `Current.session`, then builds a signed cookie value through `ActionDispatch::TestRequest.create.cookie_jar.signed[:session_id]` and copies it into the test's `cookies["session_id"]`. `sign_out` destroys the session and deletes the cookie. It was added to the generator's output in Rails 8.1.
A cloakroom ticket: the numbered stub (the signed cookie) means nothing on its own; the coat on the rack (the Session row) is what counts. Take the coat off the rack and the stub opens nothing.
- The session_id cookie holds the user's id, so the row lookup is unnecessary.
- Calling reset_session in a controller signs the generated user out.
- Current.user keeps its value between requests like a class variable.
- allow_unauthenticated_access still loads Current.user for signed-in visitors.
- Sign-out only deletes the cookie and keeps the Session row for auditing.