Skip to content

WebAuthn Authentication: From 2FA to Password-less

Master password-less authentication in Rails

Ali Fadel and Ibraheem Tuffaha

This is Part 2 of a 4-part series on implementing WebAuthn in Rails with Devise and Inertia.js.

PartTitle
1Setup and Registration
2Authentication: From 2FA to Password-less (you are here)
3Backup Codes: The Safety Net
4Design Decisions and Trade-offs

In Part 1, we set up the WebAuthn gem, created the database schema, and built passkey registration. Users can now add passkeys to their accounts.

In this post, we'll implement the full Rails authentication flow. We'll start with password-full WebAuthn 2FA (password + passkey), then add password-less authentication (passkey only) for a truly secure sign-in experience. Finally, we'll clean up the code to settle on the simpler password-less solution.

Why build 2FA first? We want to cover both common use cases. Implementing the password-full flow first ensures we understand the fundamentals of WebAuthn authentication before refactoring to the simpler password-less solution.

Note: If you only want password-less authentication, you can still read the 2FA sections for context on how the authentication flow works, but focus on the password-less and "Cleaning Up" sections for your actual implementation.

Password-Full Authentication (2FA with Passkeys)#

Now that users can register passkeys, we need to verify them during sign-in. In this password-full flow, users first enter their password, then complete 2FA with their passkey.

The Authentication Concern [Backend]#

The Authentication concern handles two things: ensuring users are signed in, and enforcing WebAuthn 2FA for users who have it enabled:

Include it in your ApplicationController:

The enforce_web_authn_verification method is the key to password-full 2FA. After a user signs in with their password, if they have WebAuthn enabled, they get redirected to the 2FA page. This method intercepts requests and ensures they complete 2FA before accessing protected routes.

It also handles edge cases: if a different user abandoned their 2FA attempt and someone else signed in, we clear the stale session.

Important: You need to skip this callback in controllers that handle public requests or the 2FA flow itself. Otherwise users would be stuck in a redirect loop:

The pattern is simple: any controller action that a user might hit before completing 2FA needs the skip.

The PendingAuthentication Concern [Backend]#

We also need a concern for controllers that handle the 2FA flow. These controllers work with users who haven't fully signed in yet. They need to retrieve the pending user from the session, complete the sign-in when verification succeeds, and clean up the session appropriately:

Let's break down what each method does.

ensure_pending_authentication is a before_action guard. It prevents users from accessing 2FA pages directly without first starting the authentication flow. If someone navigates to /web_authn/authentication/new without a pending session, they get redirected to sign-in.

pending_user retrieves the user from the session. During the 2FA flow, we store the user's ID (not the user object) in the session. This method looks them up. It returns nil if the user doesn't exist or if the session has expired.

complete_sign_in finishes the authentication. It handles several things: restoring where the user was trying to go before authentication, cleaning up the pending session, and actually signing them in. Note that we always set remember: true. This was a deliberate decision. Users who authenticate with passkeys have proven possession of a secure device, so there's no need to make them re-authenticate frequently.

The Routes [Backend]#

Add the authentication routes:

This gives us:

  • GET /web_authn/authentication/new - The 2FA page
  • POST /web_authn/authentications/challenge - Get authentication options (separate controller)
  • POST /web_authn/authentication - Verify the passkey

We put the challenge in its own controller. It's a distinct responsibility (generating options) from the main authentication controller (verifying credentials). This follows the single-responsibility principle and keeps each controller focused.

Modifying Devise's Sessions Controller [Backend]#

We modify how Devise handles sign-in to redirect users with WebAuthn to the 2FA page after they enter their password:

Let's walk through what this does.

First, we skip enforce_web_authn_verification for the sessions controller actions. This concern (defined earlier) would redirect users to 2FA, but we need to handle the sign-in flow ourselves here:

The new action clears any stale WebAuthn session. This handles the case where a user abandons 2FA and comes back to the sign-in page.

In create, we use store: false to authenticate without creating a session. This verifies the password is correct but doesn't sign them in yet:

Then we check if the user has WebAuthn enabled. If they do, we redirect them to 2FA:

We store the user's ID and the location they were trying to access in the WebAuthn session. After they complete 2FA, we'll redirect them to that location.

For users without WebAuthn, we sign them in normally with remember: true. We decided not to show a "remember me" checkbox. With modern session security, keeping users signed in is the better UX.

The Challenge Controller [Backend]#

The challenge is in its own controller. It generates authentication options:

Unlike registration, authentication uses options_for_get. The allow parameter restricts which credentials can be used. The user_verification: 'discouraged' setting matches what we used during registration. For 2FA, the password already provides one factor, so we only need the authenticator to prove presence (touch), not verify the user's identity again with a PIN or biometric. If a user has multiple passkeys, any of them will work. We store the challenge in the existing WebAuthn session.

The Authentication Controller [Backend]#

Now the controller that verifies the passkey:

Let's break down each piece.

We skip authenticate_user! because users aren't signed in yet. We skip underscore_params because the WebAuthn gem needs camelCase keys.

The new action renders the 2FA page.

The create action verifies the response defensively. Check if the user exists. Check if verification succeeds. Only then sign them in:

The valid_credential? method does the cryptographic verification and returns a boolean:

  1. Parse the credential from the browser
  2. Find the stored credential by external_id
  3. Verify the signature against the stored public key and challenge
  4. Update the sign count

The sign count update is important for detecting cloned authenticators:

If someone clones a hardware key, the sign counts will diverge. The legitimate key might have sign_count 50, but the clone starts at 0. The verification will fail because the presented count is lower than expected.

The Two-Factor Auth Page [Frontend]#

The 2FA page needs to handle several states: loading, authenticating, errors, and a fallback to backup codes (which we'll add later in Part 3). Let's build it up:

We check browser support on mount and immediately start authentication if supported. This reduces friction. Users don't have to click "Sign in with passkey" after already entering their password.

The authentication function:

The flow is: get challenge, trigger browser UI, send response to server. If authentication succeeds, the server redirects automatically (via Inertia). If it fails, we show an error and let the user retry.

The template:

The UI is simple: a title, description, error display, and a big button. If authentication is happening, we show a loading state. If it failed, users can click to retry.

We'll add backup code support to this same page later in Part 3. For now, this handles the passkey-only flow.

What Can Go Wrong#

Authentication issues to watch for:

  • Session mismatch: If a user has multiple tabs open and signs in on one, the other tab's 2FA session becomes stale. The enforce_web_authn_verification concern checks for this and clears orphaned sessions.
  • Wrong credential: Users with multiple passkeys might present the wrong one. The verification will fail because the signature doesn't match the stored public key. This is expected behavior - they just need to try their other passkey.
  • Browser doesn't support WebAuthn: Some browsers (especially older mobile browsers) don't support WebAuthn. Check for support before showing passkey options and have a fallback.

Password-Less Authentication#

Password-full works. Now let's add password-less. Users with passkeys should be able to skip the password entirely. This is where passkeys become genuinely better than passwords, not just an extra step.

The Lookup Controller [Backend]#

We need a way to check if a user has passkeys before showing them the password form. Add the routes:

The controller:

This is intentionally minimal. The lookup endpoint alone doesn't reveal whether an email exists in our system. It returns false both when the user doesn't exist and when they exist but have no passkeys.

Security note: While this endpoint is safe in isolation, an attacker could combine it with the sessions endpoint (below) to enumerate users. If lookup returns false and the sessions endpoint returns 404, the user definitely doesn't exist. If lookup returns false but sessions redirects, the user exists but has no passkeys. We accept this trade-off for simplicity, but if user enumeration is a concern for your application, you could modify the sessions controller to always redirect (storing an invalid user ID for non-existent users, so the 2FA page shows a generic "Session expired" error either way). Rate limiting on both endpoints helps mitigate enumeration attempts.

The Sessions Controller (Password-Less Path) [Backend]#

Now we need a way to start the WebAuthn flow without a password. Add another route:

This controller is intentionally simple. It uses find_by! which raises ActiveRecord::RecordNotFound if the user doesn't exist. In normal use, this endpoint is only called after the lookup confirms WebAuthn is available. However, as noted above, an attacker could use the 404 vs redirect difference to enumerate users. We accept this trade-off, relying on rate limiting to slow enumeration attempts.

The controller sets up the pending authentication session and redirects directly to the 2FA page. No JSON response, no checking web_authn_enabled?. The lookup already did that work. This keeps the controller focused on one thing: starting the password-less flow.

Adaptive Sign-In Flow [Frontend]#

Now we modify the sign-in page to check for passkeys after the user enters their email. The page has three steps: method selection (OAuth or email), email entry, and password entry. We add passkey detection between email and password.

The step-based approach lets us show different UI based on where the user is in the flow. Now the email continuation handler:

If the user has passkeys enabled, we direct them through the password-less flow. If they don't, we show the password form. If the browser doesn't support WebAuthn, the 2FA page will handle it gracefully and the user can use a backup code to complete authentication.

The password-less flow initiation:

We use Inertia's router.post() because the sessions controller redirects directly. Inertia handles the redirect automatically and navigates for us. Clean and simple.

The rest of the component handles navigation between steps and the password form:

The template uses transitions between steps for a polished feel:

What Can Go Wrong#

Password-less introduces new failure modes:

  • Email enumeration: The lookup endpoint reveals whether an email has passkeys. We accept this trade-off for UX, but you could add rate limiting or CAPTCHAs if concerned.
  • Passkey authentication fails: The browser doesn't support WebAuthn, the passkey isn't synced to this device, or user verification fails (no biometrics/PIN configured). The 2FA page shows an error; backup codes provide a fallback (see Part 3).

Cleaning Up: Removing Password-Full Infrastructure#

With password-less working, we can simplify. Users with passkeys now go directly to passkey authentication - they never enter a password. The password-full 2FA flow from earlier in this post is no longer needed.

First, simplify the Authentication concern by removing enforce_web_authn_verification:

That's it. No more enforce_web_authn_verification. Users with passkeys use the password-less flow, so we don't need to intercept requests and redirect them to 2FA.

With enforce_web_authn_verification gone, the controllers that were skipping it no longer need those skip_before_action lines. Update the Sessions controller from earlier to remove it:

The same applies to ChallengesController, AuthenticationsController, and any other controllers that were skipping enforce_web_authn_verification.

Why we still redirect to 2FA: You might wonder why we redirect WebAuthn users to the 2FA page instead of rejecting their password login. This is important for backup code access (which we'll implement in Part 3). If we rejected password login entirely, users on browsers that don't support WebAuthn (or users who don't have their passkey synced to the current device) would be completely locked out. By allowing password login to proceed to the 2FA page, they can use a backup code as a fallback.

Strengthening WebAuthn Options for Password-Less#

With password-full 2FA, we used user_verification: 'discouraged' because the password already proved the user's identity. For password-less, the passkey is the only authentication factor. We need to strengthen our settings.

Update the options controller to require user verification:

And update the challenge controller:

Why this matters: With user_verification: 'required', the authenticator must verify the user's identity (PIN, fingerprint, face) before signing the challenge. This ensures two factors:

  1. Something you have: The security key or device
  2. Something you know/are: PIN or biometric

Without this, if someone steals a user's security key, they could log in with just a touch. With user_verification: 'required', they'd also need the PIN or the user's fingerprint.

Trade-off: This excludes older security keys that don't support user verification (PIN-less keys). If you need to support those, use 'preferred' instead of 'required'. The authenticator will verify if it can, but won't fail if it can't.

Routes Added in This Part#

This gives you:

  • POST /auth/lookup - Check if user has passkeys (password-less flow)
  • POST /web_authn/session - Start password-less authentication
  • GET /web_authn/authentication/new - 2FA page
  • POST /web_authn/authentications/challenge - Get authentication challenge
  • POST /web_authn/authentication - Verify passkey

What's Next#

At this point, users can:

  • Add passkeys to their accounts
  • Sign in with passkeys (password-less)
  • Fall back to passwords if they don't have passkeys

But what happens if a user loses their phone or hardware key? They're locked out. In Part 3, we'll add backup codes - single-use recovery codes that let users regain access when they can't use their passkey.

Previous:Part 1 - Setup and Registration

Next:Part 3 - Backup Codes: The Safety Net

#engineering