Skip to content

Backup Codes for WebAuthn: The Safety Net

Learn how to implement secure backup codes for WebAuthn in Rails

Ali Fadel and Ibraheem Tuffaha

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

In Part 1, we set up WebAuthn and built passkey registration. In Part 2, we implemented authentication - first as 2FA, then as password-less.

But there's a problem. What happens when a user loses their phone? Or their hardware key breaks? They're locked out of their account with no way back in.

Backup codes solve this. They're single-use recovery codes that users can enter when they can't use their passkey. In this post, we'll implement backup code generation, storage, authentication, and regeneration.

What you'll need to update from previous parts: If you've been following along, this part requires changes to code from Parts 1 and 2:

  • The credentials controller from Part 1 gets refactored to return JSON (so we can send backup codes to the frontend)
  • The registration modal from Part 1 changes from form.post() to fetch() to handle JSON responses
  • The TwoFactorAuth page from Part 2 gets a backup code entry form added

We'll show the complete updated code for each of these.

How Backup Codes Work#

The idea is simple: when users register their first passkey, we generate 10 random codes. They save these codes somewhere safe (password manager, printed paper, etc.). If they ever lose access to their passkey, they can sign in with one of these codes. Each code only works once.

Backup Code Generation: When a user registers their first passkey, we generate backup codes automatically. The codes are shown once in a modal, and the user must save them. We only store hashed versions in the database - if someone compromises the database, they can't use the codes.

Backup Code Usage: When a user can't access their passkey (lost phone, broken hardware key), they can use a backup code instead. Each code works only once - after use, it's marked as consumed and can't be reused.

The Database Schema [Backend]#

Backup codes need their own table. Each code is stored separately rather than as an array because we need to track which codes have been used:

The columns:

  • user_id: References the user who owns the codes
  • code_digest: The BCrypt hash of the code (we never store plaintext)
  • used_at: When the code was consumed (null means unused, a timestamp means used)

The used_at column serves two purposes. First, it lets us query for unused codes (where(used_at: nil)). Second, it provides an audit trail. If you need to investigate suspicious account activity, you can see exactly when backup codes were used.

We also need fields on the User model for rate limiting:

The BackupCode Model [Backend]#

Backup codes are stored as BCrypt hashes, not plaintext. If your database is compromised, attackers can't use the codes.

The normalize method strips formatting. We display codes as XXXXX-XXXXX but accept input with or without the dash. The normalization makes verification flexible:

The mark_as_used! method includes a reload to prevent race conditions. If two requests try to use the same code simultaneously, only one will succeed:

The Generator Service [Backend]#

The generator service creates a set of backup codes for a user. It handles the full lifecycle: deleting old codes, generating new ones, hashing them securely, and returning the plaintext versions (which we show to the user once and never store).

Let's break down the design decisions.

The charset excludes ambiguous characters. 0 looks like O. 1 looks like I. Removing these prevents user errors when transcribing codes:

We use a Set to ensure uniqueness:

The transaction ensures atomicity. If hashing fails partway through, we don't end up with partial code sets:

We reset the failed attempt counter when generating new codes. If a user was locked out, regenerating codes gives them a fresh start:

The generated codes get formatted with a dash for readability. ABCDE12345 becomes ABCDE-12345. This makes it easier to read and transcribe.

Auto-Generating Codes on First Passkey Registration [Backend]#

When users register their first passkey, we automatically generate backup codes. This is important. Without backup codes, losing a passkey means losing account access.

Update the credentials controller we built in Part 1. Here's the complete version with backup code generation:

This is a significant change from the Part 1 version. We now return JSON for all responses, not just WebAuthn errors. Why? Because we need to return backup codes to the frontend on the first passkey registration. The frontend modal needs the actual codes to display them to the user.

The generate_backup_codes_if_first_credential method returns nil for subsequent passkeys (when the user already has credentials), so the JSON response will have backup_codes: null in that case. The frontend handles both cases.

Handling Backup Codes in Registration [Frontend]#

Since the backend now always returns JSON, we update the registration modal to handle the response uniformly. The key change is checking whether backup_codes is present in the response:

The response handling is now simpler. We always use fetch() and check if data.backup_codes is present. If it is (first passkey), we show the backup codes modal. If not (subsequent passkey), we complete the registration immediately.

After the user confirms they've saved their backup codes, we clean up and reload the page:

The Backup Codes Modal [Frontend]#

When backup codes are generated, users must acknowledge saving them before continuing:

The modal is non-dismissible (:close="false" and :dismissible="false"). Users can't close it by clicking outside or pressing escape. They must check the box and click the button. This ensures they've at least seen the codes.

We provide two ways to save: copy to clipboard or download as a file. The clipboard uses VueUse's useClipboard for a clean implementation. The download uses a hidden anchor element trick that works across browsers.

Backup Code Authentication [Backend]#

Add the routes:

The controller:

Let's break down the security considerations.

Rate limiting happens at two levels. Rack-level limits (5 requests per minute) prevent request flooding. Application-level limits (10 failed attempts) trigger a 30-minute lockout:

Why reset the counter when locking? Because the lock itself is the punishment. If we kept the counter at 10, the next failed attempt after unlock would immediately lock again.

Code verification iterates through unused codes and checks each one:

This is O(n) where n is at most 10, which is fine. We could add an index on the hash, but BCrypt hashes are salted so we'd need to check each one anyway.

We only mark the code as used after confirming the user can sign in:

This prevents a subtle bug. If a user's account is locked (too many failed password attempts), Devise's active_for_authentication? returns false. Without this check, we'd consume their backup code but not let them in.

What Can Go Wrong#

Backup code issues to watch for:

  • BCrypt timing: We hash codes with BCrypt (cost 12), so verification takes ~250ms per code. With 10 codes to check, worst case is 2.5 seconds. Users might think it's broken. Consider showing a loading state.
  • Rate limiting: Without limits, attackers can brute-force codes. We use both Rack-level (5/min per IP) and application-level (10 failures = 30-minute lockout) limits.
  • Code already used: Users sometimes try to reuse a code. Show a clear error message explaining the code has already been used.
  • All codes exhausted: If all codes are used, the user is locked out. Show a warning when codes are running low (e.g., "You have 2 backup codes remaining").

Adding Backup Code Entry to the 2FA Page [Frontend]#

Remember the TwoFactorAuth page from Part 2? We need to update it to handle backup code entry. Rather than navigating to a separate page, we add a toggle that lets users switch between passkey authentication and backup code entry on the same page.

First, add the state and form for backup codes:

Notice we use Inertia's useForm for backup codes but fetch() for passkeys. Why the difference? Backup code submission is a simple form post (one field, standard request/response). useForm gives us automatic loading states via backupCodeForm.processing and cleaner error handling. Passkey authentication needs the two-step fetch pattern (get challenge first, then submit response) because of the browser's WebAuthn ceremony between the two requests.

The template uses conditional rendering to switch between views:

This keeps everything on one page. Users don't navigate away to enter a backup code. They click "Use a backup code", enter it, and submit. If they change their mind, they click "Use passkey instead" to go back.

Backup Code Regeneration [Backend]#

Users need a way to regenerate codes if they're running low or think they've been compromised. Add the route:

The controller is simple because the service does all the work:

The web_authn_enabled? check prevents users from regenerating backup codes if they don't have any passkeys. This could happen if someone tries to access the endpoint directly.

The frontend shows a confirmation modal (regenerating invalidates existing codes), then displays the new codes:

Auto-Deleting Backup Codes When Last Passkey Is Removed [Backend]#

If a user removes their last passkey, we delete their backup codes too:

This prevents a confusing state where users have backup codes but nothing to back up. It also cleans up the web_authn_id since they're no longer using WebAuthn.

User Model Additions [Backend]#

Add the association and helper method:

Displaying Backup Codes Count [Backend]#

Now that users have backup codes, we should show them how many they have remaining. Update the Security controller:

The backup_codes_remaining prop tells users how many codes they have left. When it gets low, you can show a warning suggesting they regenerate their codes.

Routes Added in This Part#

This gives you:

  • POST /users/backup_codes - Regenerate backup codes
  • POST /backup_code/authentication - Authenticate with backup code

What's Next#

At this point, you have a complete WebAuthn implementation:

  • Users can register passkeys
  • Users can sign in with passkeys (password-less)
  • Users have backup codes for recovery
  • Users can regenerate backup codes when needed

In Part 4, we'll discuss the design decisions and trade-offs we made, and the race conditions we chose not to handle.

Previous:Part 2 - Authentication: From 2FA to Password-less

Next:Part 4 - Design Decisions and Trade-offs

#engineering