Devise::Webauthn is a Devise extension that adds WebAuthn support to your Rails application, allowing users to authenticate with passkeys and use security keys for two factor authentication.
- Ruby: 2.7+
- JavaScript: This gem includes WebAuthn JavaScript as custom HTML elements. You'll need to import the JavaScript file in your application.
Add this line to your application's Gemfile:
gem 'devise-webauthn'And then execute:
$ bundle install
Or install it yourself as:
$ gem install devise-webauthn
First, ensure you have Devise set up in your Rails application. For a full guide on setting up Devise, refer to the Devise documentation. Then, follow these steps to integrate Devise::Webauthn:
-
Run Devise::Webauthn Generator: Run the generator to set up necessary configurations and migrations:
$ bin/rails generate devise:webauthn:install
You can optionally specify a different resource name (defaults to "user"):
$ bin/rails generate devise:webauthn:install --resource-name=RESOURCE_NAME
The generator will:
- Create the WebAuthn initializer (
config/initializers/webauthn.rb) - Generate the
WebauthnCredentialmodel and migration - Add
webauthn_idfield to your devise model (e.g.,User) - Configure JavaScript loading for your application (see JavaScript Setup)
- Create the WebAuthn initializer (
-
Run Migrations: After running the generator, execute the migrations to update your database schema:
$ bin/rails db:migrate
-
Update Your Devise Model: Add
:passkey_authenticatableto your Devise model (e.g.,User) for passkeys authentication and:webauthn_two_factor_authenticatablefor WebAuthn-based 2FA if desired. For example:class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :passkey_authenticatable, :webauthn_two_factor_authenticatable end
-
Configure WebAuthn Settings: Update the generated initializer file
config/initializers/webauthn.rbwith your application's specific settings, such asrp_name, andallowed_origins. For example:WebAuthn.configure do |config| # This value needs to match `window.location.origin` evaluated by # the User Agent during registration and authentication ceremonies. config.allowed_origins = ["https://yourapp.com"] # Relying Party name for display purposes config.rp_name = "Your App Name" end
Tip
You can find a working example on how to use this gem for passwordless and two factor authentication in devise-webauthn-rails-demo.
-
Include bundled WebAuthn JavaScript in your application: The install generator automatically configures JavaScript loading based on your setup:
For importmap-rails:
- Adds
pin "devise/webauthn", to: "devise/webauthn.js"toconfig/importmap.rb - Adds
import "devise/webauthn"toapp/javascript/application.js
For node setups (esbuild, Bun, etc.):
- Adds
<%= javascript_include_tag "devise/webauthn" %>to your application layout
If the automatic setup doesn't work for your configuration, you can manually include the JavaScript:
<%= javascript_include_tag "devise/webauthn" %>
- Adds
When the form is submitted:
- The default form submission is prevented
- The browser's WebAuthn prompt is triggered with the provided options
- Upon successful authentication, the credential response is stored in the hidden input
- The form is submitted with the credential data
Signed-in users can add passkeys by visiting /users/passkeys/new.
When a user visits /users/sign_in they can choose to authenticate using a passkey. The authentication flow is handled by PasskeysAuthenticatable strategy.
The WebAuthn passkey sign-in flow works as follows:
- User clicks "Sign in with Passkey", starting a WebAuthn authentication ceremony.
- Browser shows available passkeys.
- User selects a passkey and verifies with their authenticator.
- The server verifies the response and signs in the user.
Signed-in users can add security keys by visiting /users/second_factor_webauthn_credentials/new.
When a user that has 2FA enabled (i.e., has registered passkeys or security keys) visits /users/sign_in, after entering their primary credentials (e.g., email and password), they will be prompted to complete the second factor authentication using WebAuthn. The authentication flow is handled by WebauthnTwoFactorAuthenticatable strategy.
The two factor authentication flow with WebAuthn works as follows:
- User enters their primary credentials (e.g., email and password) and submits the form.
- If the user has 2FA enabled, they are redirected to a second factor authentication page.
- User clicks "Use security key", starting a WebAuthn authentication ceremony.
- Browser shows available credentials (which can be both passkeys and security keys).
- User selects a credential and verifies with their authenticator.
- The server verifies the response and signs in the user.
Similar to views customization on Devise, to customize the views, you can copy the view files from the gem into your application. Run the following command:
$ bin/rails generate devise:webauthn:viewsIf you want to customize only specific views, you can copy them individually. For example, to copy only the passkeys views:
$ bin/rails generate devise:webauthn:views -v passkeysDevise::Webauthn provides helpers that can be used in your views. For example, for a resource named user, you can use the following helpers:
To add a button for logging in with passkeys:
<%= login_with_passkey_button("Log in with passkeys", session_path: user_session_path) %>To add a passkeys creation form:
<%= passkey_creation_form_for(current_user) do |form| %>
<%= form.label :name, 'Passkey name' %>
<%= form.text_field :name, required: true %>
<%= form.submit 'Create Passkey' %>
<% end %>The custom elements check for WebAuthn API support when they connect to the DOM. If the browser doesn't support WebAuthn, a webauthn:unsupported event is dispatched and the form submission handler is not attached.
document.addEventListener('webauthn:unsupported', (event) => {
const { action } = event.detail; // 'create' or 'get'
// Hide the WebAuthn form and show a message
hideWebauthnFormWithMessage('Your browser does not support WebAuthn');
});By default, WebAuthn errors during registration or authentication are displayed using the browser's alert() dialog. You can customize this behavior by listening to the webauthn:prompt:error event.
The custom elements dispatch a webauthn:prompt:error event whenever an error occurs during the WebAuthn prompt interaction (registration or authentication). You can listen for this event and provide custom error handling:
document.addEventListener('webauthn:prompt:error', (event) => {
event.preventDefault(); // Prevent the default alert
const { error, action } = event.detail;
// Your custom error handling
console.error(`WebAuthn ${action} failed:`, error);
showFlashMessage(error.message, 'error');
});The event includes the following information in event.detail:
error: The error object thrown during the WebAuthn operationaction: Either"create"(for registration) or"get"(for authentication)
WebAuthn operations can fail for various reasons. Here are some common error types you might want to handle:
document.addEventListener('webauthn:prompt:error', (event) => {
event.preventDefault();
const { error, action } = event.detail;
switch (error.name) {
case 'NotAllowedError':
// User cancelled the operation or timeout
showFlashMessage('Operation cancelled or timed out', 'warning');
break;
default:
// Generic error message
showFlashMessage(`Authentication error: ${error.message}`, 'error');
}
});You can provide different error handling based on whether the error occurred during registration or authentication:
document.addEventListener('webauthn:prompt:error', (event) => {
event.preventDefault();
const { error, action } = event.detail;
if (action === 'create') {
// Handle registration errors
handleRegistrationError(error);
} else if (action === 'get') {
// Handle authentication errors
handleAuthenticationError(error);
}
});Note: If you don't call event.preventDefault(), the default alert() will still be shown.
Similar to controllers customization on Devise, you can customize the Devise::Webauthn controllers.
- Create your custom controllers using the generator which requires a scope:
$ bin/rails generate devise:webauthn:controllers [scope]- Tell the router to use your custom controllers. For example, if your scope is
users:
devise_for :users, controllers: {
passkeys: 'users/passkeys'
}- Change or extend the generated controllers as needed.
The gem provides two custom HTML elements for WebAuthn operations. While the form helpers handle this automatically, you can use these elements directly for custom implementations.
Used for registering new credentials (passkeys or security keys).
<form action="/passkeys" method="post">
<webauthn-create data-options-json="<%= create_passkey_options(@user).to_json %>">
<input type="hidden" name="public_key_credential" data-webauthn-target="response">
<input type="text" name="name" placeholder="Passkey name">
<button type="submit">Create Passkey</button>
</webauthn-create>
</form>Requirements:
- Must be wrapped in a
<form>element- The form's action should point to the appropriate endpoint – you can use the provided url helpers:
- For creating passkeys:
passkeys_path(resource_name) - For creating 2FA security keys:
second_factor_webauthn_credentials_path(resource_name)
- For creating passkeys:
- The form's action should point to the appropriate endpoint – you can use the provided url helpers:
- Requires a
data-options-jsonattribute containing JSON-serialized WebAuthn creation options - Must contain a hidden input with
data-webauthn-target="response"to store the credential response - Must contain the submit button — the element intercepts form submission, calls the WebAuthn API, stores the credential in the hidden input, and then re-submits the form
Used for authenticating with existing credentials.
<form action="/users/sign_in" method="post">
<webauthn-get data-options-json="<%= passkey_authentication_options.to_json %>">
<input type="hidden" name="public_key_credential" data-webauthn-target="response">
<button type="submit">Sign in with Passkey</button>
</webauthn-get>
</form>Requirements:
- Must be wrapped in a
<form>element- The form's action should point to the appropriate endpoint – you can use the provided url helpers:
- For passkey sign-in:
session_path(resource_name) - For 2FA with WebAuthn:
two_factor_authentication_path(resource_name)
- For passkey sign-in:
- The form's action should point to the appropriate endpoint – you can use the provided url helpers:
- Requires a
data-options-jsonattribute containing JSON-serialized WebAuthn request options - Must contain a hidden input with
data-webauthn-target="response"to store the credential response - Must contain the submit button — the element intercepts form submission, calls the WebAuthn API, stores the credential in the hidden input, and then re-submits the form
After checking out the repo, run bin/setup to install dependencies. Then, run bundle exec rspec to run the tests.
To run the linter, use bundle exec rubocop.
Before submitting a pull request, ensure that tests and linter pass.
Bug reports and pull requests are welcome on GitHub at https://github.com/cedarcode/devise-webauthn.
The gem is available as open source under the terms of the MIT License.