Web frameworks · Intermediate · 26 min
Add sign-in to a Rails app with the built-in authentication generator
By Padding · Updated 18 Nov 2026
Rails 8.1.4.1 · Ruby 4.0 (ruby:4.0-slim)
You will have a Rails 8.1 app with sign-in, sign-out and password reset from the built-in generator, a sign-up page you add yourself, a members area that needs a session, a rate-limited login form and integration tests that prove it all works.
On this page
Until Rails 8, adding accounts to a Rails app usually meant reaching for a gem such as Devise. Rails now ships a generator that writes a plain, readable sign-in system straight into your app: a User model with has_secure_password, a Session model stored in the database, a controller concern that guards every page, and a password reset flow with an email. There is no engine hiding the logic. Every line is yours to read and change.
The generator deliberately stops short of sign-up, because who may create an account differs from app to app. In this tutorial you run it, read what it wrote, add a sign-up page, decide which pages are public and which need a session, watch the login rate limit refuse a script, and finish with integration tests. The running example is a small club website: a public home page and a members area.
It follows on from your first Rails 8 app, so rails new, bin/rails and the folder layout should already be familiar.
Step 1 · Create the app and run the generator
Confirm the Rails version, then create a fresh app in a throwaway folder:
rails -v
rails new ~/rails-auth-demo
cd ~/rails-auth-demorails new installs the gems and sets up SQLite, Hotwire and the rest of the Rails 8 defaults, which takes a minute or two. Now run the authentication generator and create the two tables it adds:
bin/rails generate authentication
bin/rails db:migrateThe generator uncomments bcrypt in the Gemfile and runs bundle install, because has_secure_password hashes passwords with bcrypt. It also writes two migrations: users with a unique, required email_address and a password_digest, and sessions with a user_id, ip_address and user_agent.
Check it worked
rails -v prints Rails 8.1.4.1. The generator prints a column of create lines that includes app/models/user.rb, app/models/session.rb, app/controllers/concerns/authentication.rb and app/mailers/passwords_mailer.rb. db:migrate ends with CreateUsers: migrated and CreateSessions: migrated.
Step 2 · Read what the generator wrote
Before you build on it, spend a few minutes with the code. List the routes it added:
bin/rails routes -c sessions
bin/rails routes -c passwordsresource :session gives you GET /session/new (the sign-in form), POST /session (sign in) and DELETE /session (sign out). resources :passwords, param: :token gives the reset flow: a form to ask for an email, and an edit page at /passwords/<token>/edit.
Now open these files in your editor, in this order:
app/models/user.rb:has_secure_passwordaddspasswordandpassword_confirmationattributes, stores only a bcrypt hash inpassword_digest, and rejects passwords longer than 72 bytes, the most bcrypt can use.normalizesstrips and lowercases the email address before it is saved or searched for.app/models/session.rbandapp/models/current.rb: each sign-in creates aSessionrow.Currentholds the session for the length of one request, so any code can ask forCurrent.user.app/controllers/concerns/authentication.rb: the heart of it.ApplicationControllernow includes this concern, which addsbefore_action :require_authenticationto every controller. It looks for a signedsession_idcookie, loads the matching row, and redirects to the sign-in form if there is none, remembering the page you wanted.start_new_session_forwrites the cookie as permanent,httponly(scripts cannot read it) andsame_site: :lax.app/controllers/sessions_controller.rb: signs in withUser.authenticate_by, which takes about the same time whether or not the email exists, so response timing does not reveal who has an account. Note therate_limitline; you test it later.app/controllers/passwords_controller.rbandapp/mailers/passwords_mailer.rb: the reset flow. A successful reset deletes all of that user's sessions, signing them out on every device.
The cookie holds only a session ID, signed with your app's secret_key_base so it cannot be forged. The real record lives in the database, which means you can end a session from the server by deleting its row. A cookie that stored the user ID alone could not be revoked that way.
Check it worked
The first command prints a table that includes a row like new_session GET /session/new(.:format) sessions#new (Rails pads the columns with spaces), a POST /session row for sessions#create and a DELETE /session row for sessions#destroy. resource also declares show, edit and update routes; the controller has no such actions, so those URLs answer with an error. The second table includes a row like edit_password GET /passwords/:token/edit(.:format) passwords#edit. In app/controllers/application_controller.rb you can see the line include Authentication.
Step 3 · Choose which pages need a session
Because the concern guards every controller, any page you add is private until you say otherwise. That is the safer default: forgetting a line locks a page, rather than exposing it. Add a public home page and a private members area.
The home controller opts out with allow_unauthenticated_access, a class method the concern defines. The members controller adds nothing, so it needs a session:
cat > app/controllers/pages_controller.rb <<'RUBY'
class PagesController < ApplicationController
allow_unauthenticated_access only: :home
def home
end
end
RUBY
cat > app/controllers/members_controller.rb <<'RUBY'
class MembersController < ApplicationController
def index
@sessions = Current.user.sessions.order(created_at: :desc)
end
end
RUBYA shared partial shows who is signed in. It calls the authenticated? helper, which loads the session from the cookie. On a public page nothing else does that, so without this call Current.user would be empty even for a signed-in member. Signing out is a form with a DELETE request, made by button_to, so a link prefetch or a crawler cannot sign anyone out:
mkdir -p app/views/shared app/views/pages app/views/members
cat > app/views/shared/_account.html.erb <<'ERB'
<%= tag.p(notice) if notice %>
<% if authenticated? %>
<p>Signed in as <%= Current.user.email_address %></p>
<%= button_to "Sign out", session_path, method: :delete %>
<% else %>
<p><%= link_to "Sign in", new_session_path %> or <%= link_to "create an account", new_registration_path %></p>
<% end %>
ERB
cat > app/views/pages/home.html.erb <<'ERB'
<%= render "shared/account" %>
<h1>Riverside Running Club</h1>
<p>Anyone can read this page. Training times and notices are in the <%= link_to "members area", members_path %>.</p>
ERB
cat > app/views/members/index.html.erb <<'ERB'
<%= render "shared/account" %>
<h1>Members area</h1>
<p>Saturday long run: 6:30 from the park gate.</p>
<h2>Where you are signed in</h2>
<ul>
<% @sessions.each do |device| %>
<li><%= device.user_agent.presence || "Unknown device" %>, from <%= device.ip_address %>, <%= time_ago_in_words(device.created_at) %> ago</li>
<% end %>
</ul>
ERBThe partial already links to a sign-up page, so write the routes for that too. Replace config/routes.rb, keeping the two lines the generator added and the health check:
cat > config/routes.rb <<'RUBY'
Rails.application.routes.draw do
resource :session
resources :passwords, param: :token
resource :registration, only: %i[ new create ]
get "members", to: "members#index"
root "pages#home"
get "up" => "rails/health#show", as: :rails_health_check
end
RUBYStart the development server in a second terminal and leave it running. Code changes from here on load without a restart:
cd ~/rails-auth-demo
bin/rails serverBack in the first terminal, ask for both pages without a cookie:
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:3000/
curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' http://127.0.0.1:3000/membersCheck it worked
The first command prints 200: the home page is public. The second prints 302 http://127.0.0.1:3000/session/new: the members area sends visitors to the sign-in form. The sign-up link on the home page does not work yet; you add its controller next.
Step 4 · Add a sign-up page
Sign-up needs rules the generator does not add: an email address that looks valid and is not already taken, and a minimum password length. Replace app/models/user.rb with the generated lines plus two validations. Twelve characters is a sensible floor for a password that is the only factor:
cat > app/models/user.rb <<'RUBY'
class User < ApplicationRecord
has_secure_password
has_many :sessions, dependent: :destroy
normalizes :email_address, with: ->(e) { e.strip.downcase }
validates :email_address, presence: true, uniqueness: true,
format: { with: URI::MailTo::EMAIL_REGEXP }
validates :password, length: { minimum: 12 }, allow_nil: true
end
RUBYallow_nil: true matters: it skips the length check when a user is saved without a new password, for example when you update another field later.
The controller follows the same shape as the generated ones. It allows visitors in, limits how often one IP address can submit the form, and signs the new member straight in with the concern's start_new_session_for. params.expect (new in Rails 8) accepts only the three fields named and returns a 400 for anything malformed:
cat > app/controllers/registrations_controller.rb <<'RUBY'
class RegistrationsController < ApplicationController
allow_unauthenticated_access only: %i[ new create ]
rate_limit to: 10, within: 3.minutes, only: :create,
with: -> { redirect_to new_registration_path, alert: "Try again later." }
def new
@user = User.new
end
def create
@user = User.new(params.expect(user: [ :email_address, :password, :password_confirmation ]))
if @user.save
start_new_session_for @user
redirect_to members_path, notice: "Welcome to the club."
else
render :new, status: :unprocessable_content
end
end
end
RUBYThe 422 Unprocessable Content status on failure is what tells Turbo to show the form again with its errors. Now the view:
mkdir -p app/views/registrations
cat > app/views/registrations/new.html.erb <<'ERB'
<h1>Create an account</h1>
<%= tag.div(flash[:alert], style: "color:red") if flash[:alert] %>
<% if @user.errors.any? %>
<ul style="color:red">
<% @user.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
<%= form_with model: @user, url: registration_path do |form| %>
<div>
<%= form.label :email_address %>
<%= form.email_field :email_address, required: true, autofocus: true, autocomplete: "username" %>
</div>
<div>
<%= form.label :password %>
<%= form.password_field :password, required: true, autocomplete: "new-password", minlength: 12, maxlength: 72 %>
</div>
<div>
<%= form.label :password_confirmation %>
<%= form.password_field :password_confirmation, required: true, autocomplete: "new-password", maxlength: 72 %>
</div>
<%= form.submit "Create account" %>
<% end %>
<p><%= link_to "Already a member? Sign in", new_session_path %></p>
ERBFinally, point people from the generated sign-in form to the new page. Appending a line leaves the generated markup untouched:
cat >> app/views/sessions/new.html.erb <<'ERB'
<p><%= link_to "New here? Create an account", new_registration_path %></p>
ERBThe browser attributes (required, minlength) save a round trip on a slow connection, which helps members on prepaid mobile data, but the model validations are what actually protect you: anyone can send a request without the form.
Check it worked
Open http://localhost:3000/registration/new in a browser. Type a five-character password and press the button: the browser refuses to submit and shows its own message about the minimum length, because the field has minlength: 12. Rails never sees that request; the server-side "is too short" message is what the "rejects a taken address and a short password" test checks later. Fill the form in properly and you land on the members area with "Welcome to the club." and "Signed in as" followed by your address in lower case. The list under "Where you are signed in" shows your browser. Press Sign out and you land on the sign-in form. Sign in there and you go to the home page, because there is no saved return URL. Visiting /members now works.
Step 5 · Look at the password reset email
The reset flow works without changes. PasswordsController#create looks the address up and, only if it exists, queues PasswordsMailer.reset with deliver_later. Either way it shows the same message, so the form cannot be used to find out who is a member. The email links to a token from password_reset_token, which has_secure_password provides: it expires after 15 minutes and stops working once the password changes.
You do not need a mail server to see the email. The generator also wrote a mailer preview in test/mailers/previews/, and Rails serves previews in development. It uses the first user in the database, which is the account you just created. Ask for the plain-text part:
curl -s "http://127.0.0.1:3000/rails/mailers/passwords_mailer/reset?part=text%2Fplain"The link host comes from config.action_mailer.default_url_options, which is localhost:3000 in development. Before you deploy, set it to your real domain in config/environments/production.rb and add SMTP settings there, with the user name and password read from bin/rails credentials:edit or environment variables, never typed into the file.
Check it worked
The command prints the email body: "You can reset your password on", then a link of the form http://localhost:3000/passwords/<long token>/edit, then "This link will expire in 15 minutes." For the HTML version with the subject line, open http://localhost:3000/rails/mailers/passwords_mailer/reset in your browser.
Step 6 · Watch the rate limit stop a password guesser
Look again at the rate_limit line near the top of app/controllers/sessions_controller.rb:
rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_path, alert: "Try again later." }It counts sign-in attempts per IP address and, from the eleventh within three minutes, runs the with: block instead of the action. The count lives in the Rails cache: in development that is an in-memory store inside the server process.
Play the attacker. This loop fetches the sign-in form once for its authenticity token and cookie, the way a browser would, then posts a wrong password twelve times and prints the message each response shows. The cookie jar and form copy go in the app's tmp/ folder:
curl -s -c tmp/guess-jar -b tmp/guess-jar -o tmp/guess-form.html http://127.0.0.1:3000/session/new
token=$(grep -o 'name="authenticity_token" value="[^"]*"' tmp/guess-form.html | head -n 1 | sed 's/.*value="//; s/"$//')
for attempt in $(seq 1 12); do
printf '%s: ' "$attempt"
curl -s -L -c tmp/guess-jar -b tmp/guess-jar \
--data-urlencode "authenticity_token=$token" \
--data-urlencode "email_address=nobody@example.com" \
--data-urlencode "password=wrong-password" \
http://127.0.0.1:3000/session | grep -o 'Try [a-z ]*' | head -n 1
done | tee tmp/guess-output.txtTwo things to carry into production. First, the store must be shared by every server process, or each process keeps its own count; check config.cache_store in config/environments/production.rb, which a new Rails 8.1 app points at Solid Cache in its database. Second, the limit is per IP address, and many mobile networks put lots of customers behind one shared address. Ten attempts in three minutes is generous enough for that, but if you tighten it, a busy evening on one network could lock out members who did nothing wrong.
The test environment uses a null cache store, so the limit never triggers in your tests. That is why the generated tests can sign in as often as they like.
Check it worked
Lines 1 to 10 print Try another email address or password and lines 11 and 12 print Try again later. If you signed in from the browser in the last three minutes, the change comes a line or two earlier. To clear the count, wait three minutes or restart the server.
Step 7 · Prove it with integration tests
The generator wrote tests too: test/models/user_test.rb, test/controllers/sessions_controller_test.rb, test/controllers/passwords_controller_test.rb, fixtures for two users whose password is password, and a sign_in_as helper in test/test_helpers/. They are your tests now, and one of them breaks against your new rule: its "update" test resets the password to new, three characters. Replace the file with the same tests, using a password that meets the twelve-character minimum:
cat > test/controllers/passwords_controller_test.rb <<'RUBY'
require "test_helper"
class PasswordsControllerTest < ActionDispatch::IntegrationTest
setup { @user = User.take }
test "new" do
get new_password_path
assert_response :success
end
test "create" do
post passwords_path, params: { email_address: @user.email_address }
assert_enqueued_email_with PasswordsMailer, :reset, args: [ @user ]
assert_redirected_to new_session_path
follow_redirect!
assert_notice "reset instructions sent"
end
test "create for an unknown user redirects but sends no mail" do
post passwords_path, params: { email_address: "missing-user@example.com" }
assert_enqueued_emails 0
assert_redirected_to new_session_path
follow_redirect!
assert_notice "reset instructions sent"
end
test "edit" do
get edit_password_path(@user.password_reset_token)
assert_response :success
end
test "edit with invalid password reset token" do
get edit_password_path("invalid token")
assert_redirected_to new_password_path
follow_redirect!
assert_notice "reset link is invalid"
end
test "update" do
assert_changes -> { @user.reload.password_digest } do
put password_path(@user.password_reset_token), params: { password: "a-new-long-passphrase", password_confirmation: "a-new-long-passphrase" }
assert_redirected_to new_session_path
end
follow_redirect!
assert_notice "Password has been reset"
end
test "update with non matching passwords" do
token = @user.password_reset_token
assert_no_changes -> { @user.reload.password_digest } do
put password_path(token), params: { password: "no", password_confirmation: "match" }
assert_redirected_to edit_password_path(token)
end
follow_redirect!
assert_notice "Passwords did not match"
end
private
def assert_notice(text)
assert_select "div", /#{text}/
end
end
RUBYOne side effect is worth knowing: PasswordsController#update shows "Passwords did not match" for any failed save, so a too-short new password gets that message too. Change the alert to show @user.errors.full_messages.to_sentence if your members find it confusing.
Now write an integration test for the parts you built. Integration tests go through routing, the concern and the cookie jar exactly as a browser request does:
mkdir -p test/integration
cat > test/integration/club_access_test.rb <<'RUBY'
require "test_helper"
class ClubAccessTest < ActionDispatch::IntegrationTest
test "home page is public" do
get root_path
assert_response :success
assert_select "a", "Sign in"
end
test "members area sends visitors to sign in, then back again" do
get members_path
assert_redirected_to new_session_path
post session_path, params: { email_address: users(:one).email_address, password: "password" }
assert_redirected_to members_url
follow_redirect!
assert_select "p", /Signed in as one@example.com/
end
test "sign up creates a member and signs them in" do
assert_difference -> { User.count }, 1 do
post registration_path, params: { user: {
email_address: " Amina@Example.com",
password: "a-long-passphrase-71",
password_confirmation: "a-long-passphrase-71"
} }
end
assert_redirected_to members_path
assert cookies[:session_id].present?
follow_redirect!
assert_select "p", /Signed in as amina@example.com/
end
test "sign up rejects a taken address and a short password" do
assert_no_difference -> { User.count } do
post registration_path, params: { user: {
email_address: "ONE@example.com",
password: "short",
password_confirmation: "short"
} }
end
assert_response :unprocessable_content
assert_select "li", /has already been taken/
assert_select "li", /is too short/
end
test "signing out ends the session" do
sign_in_as users(:one)
delete session_path
assert_redirected_to new_session_path
get members_path
assert_redirected_to new_session_path
end
end
RUBY
bin/rails testThe "taken address" test sends ONE@example.com on purpose: it only passes because normalizes lowercases the address before the uniqueness check runs.
Check it worked
The run ends with 17 runs, a count of assertions, and 0 failures, 0 errors, 0 skips. To see a test catch a real mistake, add allow_unauthenticated_access as the first line inside MembersController and run bin/rails test test/integration again: the members-area and sign-out tests report errors, because the page no longer redirects and Current.user is empty. Remove the line afterwards.
Step 8 · Get it ready for real members
Before anyone else signs in, check these:
- HTTPS: passwords and the session cookie must only travel encrypted. The generated
config/environments/production.rbsetsconfig.force_ssl = trueandconfig.assume_ssl = true, which redirect to HTTPS and mark cookiessecure. Keep them on and put the app behind a TLS proxy. - Email: set the production mail host and SMTP settings, and make sure a job runner is processing the queue, because
deliver_laterhands the reset email to Active Job. A reset email that never arrives locks members out. - Old browsers:
rails newputsallow_browser versions: :moderninApplicationController, which answers older browsers (for example Chrome before version 120) with a406 Not Acceptablepage. Many people, in Africa and elsewhere, use low-end Android phones whose browsers may lag behind. If your members do, remove that line or relax it so they can reach the sign-in form at all. - Shared devices: where members sign in on a family phone or at a cyber café, the "Where you are signed in" list and a visible Sign out button matter. A next step is a button that deletes the member's other
Sessionrows, which signs them out everywhere else at once.
Stop the development server with Ctrl+C in its terminal.
When you have finished experimenting, remove the demo app:
cd ~
rm -rf ~/rails-auth-demoCheck it worked
ls ~/rails-auth-demo reports No such file or directory, and http://localhost:3000/ no longer answers.
Next steps
- Go back over models, associations and the test runner from the start: build your first Rails 8.1 app.
- Compare the same job in Python, where the framework ships the views and you write the templates: add sign-up, login and password reset to a Django app.
- Brush up on the language itself: hello world in Ruby.
Part of these paths
Related tutorials
- Build your first Rails 8.1 app with SQLiteYou will build a small club-membership app in Rails 8.1 on Ruby 4.0, with two models joined by a has_many association, validations, hand-written routes and controllers, views built from partials, a passing test suite and a clear picture of what Solid Queue and Solid Cache do in production.
- Add sign-up, login and password reset to a Django appYou will have a Django 6.1 notes app with a custom user model, sign-up, login, logout and a working password reset, where each user sees only their own notes and a test suite proves it.
- Hello World in Ruby: irb, puts and a first gem with BundlerYou will install Ruby 4.0, see how puts, print and p differ in irb, run a script that greets the user with a block, and print a table with your first gem managed by Bundler.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials