Understanding Rails

Understanding Rails · Season 4: Controllers, routing and auth

The authentication generator, line by line

Episode 30 · deep dive · about 6 minutes · Rails 8.1 · by

How was this episode?

The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.

Was it clear?

Not endorsed yet. Are you a Rails developer? What's an endorsement?

Endorse this version To endorse: create an account, confirm your email, then link GitHub.

What changed

  • Version 2, November 20, 2026: Sign-out answers 303, not 302, and each sign-in makes its own session.

Every file bin/rails generate authentication writes, and how it works.

Free to watch. If it helped, support the series.

Transcript

0:00 The authentication generator, line by line

Episode thirty. The authentication generator, line by line. Rails eight can write sign in for you. One command, and your app has users, sessions, and password resets, as plain code you own. Today we read every part of it, and run it.

0:19 What it writes

Bin rails generate authentication. It adds the bcrypt gem, writes two migrations, three models, two controllers, a concern, a mailer, the views, the routes, and tests. Notice one thing it doesn't write: a sign up page. Creating users is left to you.

0:37 Users and sessions

The migrations make two tables. Users has an email address and a password digest, both required, with a unique index on the email. Sessions belongs to a user, and keeps the IP address and the browser it came from.

0:53 has_secure_password

The user model is three lines. Has secure password is the important one. Create a user, and the password itself is never stored. Only a bcrypt digest is: sixty characters, starting with dollar two a, dollar twelve, which is how hard bcrypt worked to make it.

1:11 A normalized email

The email is normalized, as in episode twenty three: stripped and lowercased. Sam at example dot com, typed with capitals and spaces, is saved as plain lowercase sam at example dot com.

1:26 The 72-byte limit

Has secure password also adds validations. One is easy to miss: bcrypt only reads the first seventy two bytes of a password, so Rails refuses anything longer. Seventy three characters: password is too long. The sign in form sets a matching max length.

1:44 authenticate_by

To check a password, the sessions controller calls authenticate by, with the email and the password. The right pair returns the user. A wrong password returns nil. So does an email nobody has. And it takes the same time either way, because it digests the password even when there's no user, so timing can't reveal which emails exist.

2:07 Session and Current

Each sign in creates its own row in sessions, so you can be signed in on a phone and a laptop at once. Current holds the session for this request, and Current dot user is delegated to it. Episode thirty one uses that to decide who may do what.

2:24 require_authentication

The concern does the work, and the application controller includes it. So every controller now starts with a before action: require authentication. It looks for a session from the cookie. If there isn't one, it remembers the page you asked for, and redirects to sign in. Our notes page, signed out, now answers with a redirect to session new.

2:46 allow_unauthenticated_access

Some pages must stay open. Allow unauthenticated access skips that check. The sessions controller allows new and create, or nobody could ever sign in. The passwords controller allows everything, since you reset a password because you can't sign in.

3:03 The session cookie

Start new session for creates the session row, and sets a cookie, session id: signed, permanent, HTTP only and same site lax. Permanent means twenty years. The cookie is signed, not encrypted, because it only holds an id, as episode twenty nine showed. The real proof is the row. Delete the row, and the cookie means nothing.

3:25 Signing in

Here it is running. A wrong password redirects back, with try another email address or password. That message is the same whether or not the email exists. The right password redirects to the page you first asked for, the notes. And now the notes page answers two hundred.

3:45 Signing out

Signing out is delete session. Terminate session destroys the row, and deletes the cookie. The redirect takes you back to sign in.

3:54 The rate limit

The sign in action is rate limited: ten attempts within three minutes. We sent eleven wrong passwords from one address. Attempts one to ten got try another email address or password. The eleventh got try again later. The limit counts per IP address, and keeps its counts in the cache store. Episode thirty two looks at that closely.

4:16 Password resets

Password resets work by email. Ask for one, and the answer is always the same: reset instructions sent, if a user with that email address exists. So, again, nobody learns which emails have accounts. The email holds a link with a signed token, good for fifteen minutes.

4:35 The reset token

The token is tied to the current password. Change the password, and the old link stops working: find by password reset token returns nil. And a successful reset destroys every session the user had, so anyone signed in with the old password is signed out.

4:53 Action Cable

Action Cable gets the same rule. Its connection finds the session from the same signed cookie, or rejects the connection.

5:02 The tests, and a root route

The generator writes tests too, and a helper, sign in as. Run the whole suite, and two things break. First, signing in redirects to root url, and this app had no root route: undefined method root url. One line fixes it: root notes index.

5:19 What breaks

Second, every existing controller test now gets a redirect to sign in, instead of a page. Call sign in as in each test's setup, and they pass. Episode twenty's query count changed too: from four to five. Every signed in request now looks up its session.

5:37 What it leaves out

Know what it leaves out. No sign up, no email confirmation, no remember me box, since every session is permanent, and no roles. Those are yours to add, on top of code you can read.

5:50 The rules

So: the generator gives you sessions in the database, a signed cookie, bcrypt digests, and rate limits. Add a root route, sign in in your tests, and build sign up yourself. Read the code it writes. It's short.

6:05 Next

Next: authorization, without a gem.

Check your understanding

  1. User.authenticate_by is given an email address nobody has. What does it do?

    • Raises ActiveRecord::RecordNotFound
    • Returns nil right away, without hashing anything
    • Returns nil, after digesting the password anyway
    Show answer

    Returns nil, after digesting the password anyway. It digests the password whether or not a user is found, so how long it takes can't reveal which email addresses have accounts. Source: authenticate_by (Rails API 8.1).

  2. After running the generator, a signed-out visitor opens /notes. What happens?

    • The page loads, because notes don't need sign-in
    • Rails remembers the address and redirects to the sign-in page
    • Rails answers 401 Unauthorized
    Show answer

    Rails remembers the address and redirects to the sign-in page. Every controller now runs require_authentication. With no session, it stores the requested URL and redirects to new_session_path. Source: The generated Authentication concern (Rails source, v8.1.4.1).

  3. What does has_secure_password do with a 73-byte password?

    • Refuses it: the password is too long
    • Saves it, using only the first 72 bytes
    • Splits it into two digests
    Show answer

    Refuses it: the password is too long. bcrypt reads only the first 72 bytes, so has_secure_password validates that a password is no longer than that. Source: has_secure_password (Rails API 8.1).

  4. A user resets their password. What happens to the reset link they used, and to their other sessions?

    • The link keeps working for 15 minutes, and sessions stay
    • The link stops working, and every session is destroyed
    • The link stops working, and only this browser's session is kept
    Show answer

    The link stops working, and every session is destroyed. The token is tied to the password, so changing it invalidates the link. The generated update action also destroys all the user's sessions. Source: The generated PasswordsController (Rails source, v8.1.4.1).

Sources

Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.2.

Comments

Sign in to comment or sign up.