devise-webauthn 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ruby.yml +4 -0
  3. data/.gitignore +6 -6
  4. data/.rspec +1 -0
  5. data/.rspec-api +4 -0
  6. data/.rubocop.yml +1 -0
  7. data/CHANGELOG.md +34 -0
  8. data/Gemfile.lock +1 -1
  9. data/README.md +154 -1
  10. data/Rakefile +6 -1
  11. data/app/controllers/devise/passkey_authentication_options_controller.rb +4 -3
  12. data/app/controllers/devise/passkey_registration_options_controller.rb +6 -11
  13. data/app/controllers/devise/passkeys_controller.rb +30 -15
  14. data/app/controllers/devise/second_factor_webauthn_credentials_controller.rb +45 -18
  15. data/app/controllers/devise/security_key_authentication_options_controller.rb +9 -4
  16. data/app/controllers/devise/security_key_registration_options_controller.rb +8 -13
  17. data/app/controllers/devise/two_factor_authentications_controller.rb +7 -3
  18. data/lib/devise/models/webauthn_credential_authenticatable.rb +9 -0
  19. data/lib/devise/strategies/database_authenticatable.rb +29 -5
  20. data/lib/devise/strategies/passkey_authenticatable.rb +15 -11
  21. data/lib/devise/strategies/webauthn_two_factor_authenticatable.rb +20 -17
  22. data/lib/devise/webauthn/challenge_store_access.rb +15 -0
  23. data/lib/devise/webauthn/challenge_stores/cache.rb +63 -0
  24. data/lib/devise/webauthn/challenge_stores/session.rb +32 -0
  25. data/lib/devise/webauthn/credential_properties.rb +25 -0
  26. data/lib/devise/webauthn/engine.rb +6 -1
  27. data/lib/devise/webauthn/pending_two_factor_sign_in.rb +42 -0
  28. data/lib/devise/webauthn/public_key_credential_param.rb +26 -0
  29. data/lib/devise/webauthn/test/authenticator_helpers.rb +9 -6
  30. data/lib/devise/webauthn/two_factor_token.rb +31 -0
  31. data/lib/devise/webauthn/version.rb +1 -1
  32. data/lib/devise/webauthn.rb +9 -0
  33. data/lib/generators/devise/webauthn/install/templates/webauthn.rb +3 -0
  34. data/lib/generators/devise/webauthn/templates/controllers/passkey_authentication_options_controller.rb.tt +2 -2
  35. data/lib/generators/devise/webauthn/templates/controllers/passkey_registration_options_controller.rb.tt +2 -2
  36. data/lib/generators/devise/webauthn/templates/controllers/security_key_authentication_options_controller.rb.tt +2 -2
  37. data/lib/generators/devise/webauthn/templates/controllers/security_key_registration_options_controller.rb.tt +2 -2
  38. data/lib/generators/devise/webauthn/webauthn_credential_model/templates/webauthn_credential_migration.rb.erb +2 -0
  39. metadata +9 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c039d53d50190463a09e6d200c50d48674db9545daee3836f450a86c1e094877
4
- data.tar.gz: fb01adaaa26d0c9680d306c1b8e57d93f8a39f924f5ecf418f0f644ab292ed33
3
+ metadata.gz: 5a9a76f603c89a4275a75faf711d7c0f9b51766a9297b8539c4aa12e0a0ba258
4
+ data.tar.gz: cd6c4ff229442ff2e68f4cfe39647b47586e52213d3c5db1dcc2e9d8879deecb
5
5
  SHA512:
6
- metadata.gz: a9480a0988fae9eea243d01671261fd1bff0b788e4c5c34ffd956efa949fee9523c6687cb83d8663ee77aafb487038c5bd030e4d6a12e73267018941b66b15f6
7
- data.tar.gz: d38062d34035350897ecae267fc5eedcffd1a9d0230d6d9d6407ae3d572aaa828b718635e1517af7f16c92a2183123e78c98de8c51dac6ede44330a74c7f8421
6
+ metadata.gz: c3f7c145ee045fc781b6906976802782a165653a03a8ae8c06f04fecdb9d39be49fabb4272e2b4a637f0381a54a832fa59cc4b4511cf4ab810061c1eee5598eb
7
+ data.tar.gz: a696914b13d539d29e61947f0753462d952a89bcba78cdd652d6f5bb3271f238201124dc9f6f5c29d2fbe338f8303e357cb3925f786dc912308678cfe9db13b4
@@ -85,3 +85,7 @@ jobs:
85
85
 
86
86
  - name: Run tests
87
87
  run: bundle exec rspec
88
+
89
+ - name: Run API app tests
90
+ if: ${{ !cancelled() }}
91
+ run: bundle exec rake spec:api
data/.gitignore CHANGED
@@ -15,11 +15,11 @@
15
15
  .rspec_status
16
16
 
17
17
  # combustion files
18
- /spec/internal/db/*.sqlite
19
- /spec/internal/db/*.sqlite-*
20
- /spec/internal/log/*.log
21
- /spec/internal/storage/
22
- /spec/internal/tmp/
23
- /spec/internal/.byebug_history
18
+ /spec/internal*/db/*.sqlite
19
+ /spec/internal*/db/*.sqlite-*
20
+ /spec/internal*/log/*.log
21
+ /spec/internal*/storage/
22
+ /spec/internal*/tmp/
23
+ /spec/internal*/.byebug_history
24
24
 
25
25
  /gemfiles/*.gemfile.lock
data/.rspec CHANGED
@@ -1,2 +1,3 @@
1
1
  --color
2
2
  --require spec_helper
3
+ --exclude-pattern spec/api/**/*_spec.rb
data/.rspec-api ADDED
@@ -0,0 +1,4 @@
1
+ --color
2
+ --require api_spec_helper
3
+ --default-path spec/api
4
+ -I spec
data/.rubocop.yml CHANGED
@@ -9,6 +9,7 @@ AllCops:
9
9
  NewCops: enable
10
10
  Exclude:
11
11
  - "spec/internal/**/*"
12
+ - "spec/internal_api/**/*"
12
13
  - "spec/tmp/**/*"
13
14
  - "vendor/**/*"
14
15
  - "gemfiles/**/*"
data/CHANGELOG.md CHANGED
@@ -2,6 +2,40 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## [v0.6.0](https://github.com/cedarcode/devise-webauthn/compare/v0.5.1...v0.6.0/) - 2026-11-26
6
+
7
+ Before you update, add two columns to `webauthn_credentials`. See [Upgrading to v0.6.0](README.md#to-v060).
8
+
9
+ ### Added
10
+
11
+ - Add `Devise::Webauthn.challenge_store` to configure where WebAuthn challenges are kept between the options request and the verification request. It takes a symbol such as `:session`, or a store class. The default, `:session`, keeps them in the session as before. [#150](https://github.com/cedarcode/devise-webauthn/pull/150) [@RenzoMinelli]
12
+ - Add the `:cache` challenge store, which keeps challenges in `Rails.cache` instead of the session. [#152](https://github.com/cedarcode/devise-webauthn/pull/152) [@RenzoMinelli]
13
+ - Respond `401` to a non-navigational password sign-in that needs a second factor. When `skip_session_storage` includes `:params_auth`, the response includes a `two_factor_token`, and two-factor sign-in reads it from the request body instead of the session. The gem adds `two_factor_token` to `filter_parameters`. [#153](https://github.com/cedarcode/devise-webauthn/pull/153) [@RenzoMinelli]
14
+ - Accept `public_key_credential` as a JSON object as well as a JSON string. [#153](https://github.com/cedarcode/devise-webauthn/pull/153) [@RenzoMinelli]
15
+ - Respond with `201` or `204`, or `422` with JSON `errors`, from the passkey and security key controllers when the request is not navigational. [#153](https://github.com/cedarcode/devise-webauthn/pull/153) [@RenzoMinelli]
16
+ - Store whether a passkey or security key is discoverable in `webauthn_credentials.discoverable`, and whether it verified the user when it was added in `webauthn_credentials.uv_initialized`. Passkeys are always stored as discoverable, because their registration options require a discoverable credential. The security key registration options request the `credProps` extension, and the gem stores the `rk` value that the browser reports. [#170](https://github.com/cedarcode/devise-webauthn/pull/170) [@RenzoMinelli]
17
+ - Add `webauthn_user_name` to the Devise model. The passkey and security key registration options send it as the WebAuthn `user.name` and `displayName`. It defaults to the first authentication key with a non-nil value, as before; override it when that key is virtual, such as a `login` attribute. [#163](https://github.com/cedarcode/devise-webauthn/pull/163) [@RenzoMinelli]
18
+
19
+ ### Changed
20
+
21
+ - The pending two-factor sign-in is kept in the session as an encrypted `two_factor_token` instead of the user id. It expires after 5 minutes and only works for the Devise scope that issued it. Sign-ins pending during the upgrade must start again. [#154](https://github.com/cedarcode/devise-webauthn/pull/154) [@RenzoMinelli]
22
+ - Passkey sign-in and two-factor sign-in with a security key no longer store the user in the session when `skip_session_storage` includes `:params_auth`, the same as password sign-in. [#153](https://github.com/cedarcode/devise-webauthn/pull/153) [@RenzoMinelli]
23
+ - The WebAuthn options controllers only call `skip_forgery_protection` when it is defined, so they load under an `ActionController::API` parent. [#153](https://github.com/cedarcode/devise-webauthn/pull/153) [@RenzoMinelli]
24
+ - BREAKING!: Adding a passkey or security key now writes `webauthn_credentials.discoverable` and `webauthn_credentials.uv_initialized`, so add the columns in a migration before you update the gem. See [Upgrading to v0.6.0](README.md#to-v060). Upgrading a security key to a passkey (`PATCH /users/second_factor_webauthn_credentials/:id`) now fails unless both are `true`, and responds `422` with `errors` to API clients. Before, it promoted any security key, including ones that cannot sign in as a passkey or that have no user verification set up. Security keys added before this change have both set to `false`, so they cannot be upgraded. A security key's `discoverable` is also `false` when the browser does not report `credProps`, as in native iOS apps. Show the upgrade button only when `security_key.discoverable? && security_key.uv_initialized?`. If you override `verify_and_save_security_key`, store both values too: `credential_record_attributes(credential)` returns them. [#170](https://github.com/cedarcode/devise-webauthn/pull/170) [@RenzoMinelli]
25
+ - Security key registration options ask for `userVerification: "preferred"` instead of `"discouraged"`. Security keys with user verification set up ask for it when they are added. Two-factor sign-in still asks for `"discouraged"`. [#170](https://github.com/cedarcode/devise-webauthn/pull/170) [@RenzoMinelli]
26
+ - BREAKING!: The registration options controllers no longer have the private `resource_human_palatable_identifier` method. If you overrode it in your own controller, override `webauthn_user_name` in your model instead. [#163](https://github.com/cedarcode/devise-webauthn/pull/163) [@RenzoMinelli]
27
+
28
+ ### Fixed
29
+
30
+ - The controllers from `devise:webauthn:controllers` show `POST #create` in the comments of the options controllers instead of `GET #index`, which the options endpoints stopped using in v0.5.0. [#165](https://github.com/cedarcode/devise-webauthn/pull/165) [@RenzoMinelli]
31
+ - Two-factor sign-in runs only the `webauthn_two_factor_authenticatable` strategy. When a passkey challenge was pending in the session and the two-factor challenge was not, the passkey strategy took the request, consumed the passkey challenge and answered with a passkey error. [#164](https://github.com/cedarcode/devise-webauthn/pull/164) [@RenzoMinelli]
32
+ - Passkey registration options send `requireResidentKey: true` next to `residentKey: "required"`. [#166](https://github.com/cedarcode/devise-webauthn/pull/166) [@RenzoMinelli]
33
+ - The pending two-factor sign-in follows a per-request `request.env["devise.skip_storage"]`, as Devise's strategies do. An app that sets it on API requests, and keeps `:params_auth` out of `skip_session_storage` for its cookie sign-ins, now gets the `two_factor_token` in the response and reads it from the request body. Before, two-factor sign-in could not complete without a session cookie. [#167](https://github.com/cedarcode/devise-webauthn/pull/167) [@RenzoMinelli]
34
+ - The passkey and security key controllers build the redirect path (`after_update_path` and the others) only for navigational requests. In an app that routes only their JSON actions, a request with `Accept: application/json` no longer raises `NoMethodError` when it deletes or promotes a credential, or fails to add one. [#162](https://github.com/cedarcode/devise-webauthn/pull/162) [@RenzoMinelli]
35
+ - Passkey sign-in runs only in actions that call `allow_params_authentication!`, as `Devise::SessionsController#create` does. Before, the passkey strategy ran on any request that authenticated the scope (`authenticate_user!`, `current_user`), so an answer to a pending challenge signed the user in from any page or API endpoint, skipping the checks of the app's `sessions#create`. A controller of your own that calls `warden.authenticate(:passkey_authenticatable, ...)` must now call `allow_params_authentication!` first. [#168](https://github.com/cedarcode/devise-webauthn/pull/168) [@RenzoMinelli]
36
+ - The `webauthn_two_factor_authenticatable` strategy is no longer one of the scope's default strategies, so it runs only in `Devise::TwoFactorAuthenticationsController#create`. Before, after the password step, an answer to the security key challenge sent to any page that authenticated the scope, or to `sessions#create`, finished the sign-in there and skipped the two-factor controller. A two-factor controller that overrides `create` and calls `warden.authenticate!(auth_options)` must now name the strategy: `warden.authenticate!(:webauthn_two_factor_authenticatable, auth_options)`. [#169](https://github.com/cedarcode/devise-webauthn/pull/169) [@RenzoMinelli]
37
+ - Passkey and security key registration keep separate challenges. `POST /users/passkeys` accepts only a challenge from the passkey registration options, and `POST /users/second_factor_webauthn_credentials` only one from the security key registration options. Before, a credential made for one could be added as the other. Registrations pending during the upgrade must start again. [#185](https://github.com/cedarcode/devise-webauthn/pull/185) [@RenzoMinelli]
38
+
5
39
  ## [v0.5.1](https://github.com/cedarcode/devise-webauthn/compare/v0.5.0...v0.5.1/) - 2026-11-04
6
40
 
7
41
  ### Fixed
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- devise-webauthn (0.5.1)
4
+ devise-webauthn (0.6.0)
5
5
  devise (>= 4.9)
6
6
  webauthn (~> 3.0)
7
7
 
data/README.md CHANGED
@@ -99,6 +99,34 @@ When the form is submitted:
99
99
  3. Upon successful authentication, the credential response is stored in the hidden input
100
100
  4. The form is submitted with the credential data
101
101
 
102
+ ## Upgrading
103
+
104
+ ### To v0.6.0
105
+
106
+ v0.6.0 writes two new columns when a user adds a passkey or a security key: `webauthn_credentials.discoverable` and `webauthn_credentials.uv_initialized`. Without them, adding a passkey or a security key fails. Add them in a migration before you update the gem, or in the same deploy:
107
+
108
+ ```bash
109
+ $ bin/rails generate migration AddDiscoverableAndUvInitializedToWebauthnCredentials
110
+ $ bin/rails db:migrate
111
+ ```
112
+
113
+ Fill in the generated migration:
114
+
115
+ ```ruby
116
+ class AddDiscoverableAndUvInitializedToWebauthnCredentials < ActiveRecord::Migration[8.1]
117
+ def change
118
+ add_column :webauthn_credentials, :discoverable, :boolean, null: false, default: false
119
+ add_column :webauthn_credentials, :uv_initialized, :boolean, null: false, default: false
120
+ end
121
+ end
122
+ ```
123
+
124
+ Security keys added before the upgrade get `false` in both columns. They still work for two-factor sign-in, but they cannot be upgraded to passkeys. To use one as a passkey, a user can remove it and add the key again as a passkey. See [Upgrading Security Keys to Passkeys](#upgrading-security-keys-to-passkeys).
125
+
126
+ New apps do not need this step. `devise:webauthn:install` creates both columns.
127
+
128
+ v0.6.0 has other breaking changes for apps that customize the gem's controllers or views. See the [CHANGELOG](CHANGELOG.md).
129
+
102
130
  ## How It Works
103
131
 
104
132
  ### Passkey authentication
@@ -120,10 +148,25 @@ The WebAuthn passkey sign-in flow works as follows:
120
148
  #### Adding Security Keys for 2FA
121
149
  Signed-in users can add security keys by visiting `/users/second_factor_webauthn_credentials/new`.
122
150
 
151
+ #### Upgrading Security Keys to Passkeys
152
+ A security key can become a passkey only if two things are true:
153
+
154
+ - It is [discoverable](https://www.w3.org/TR/webauthn-3/#discoverable-credential). Passkey sign-in does not tell the browser which credential to use, so the browser only finds discoverable ones. Many hardware security keys create non-discoverable credentials when they are added for 2FA.
155
+ - It verified the user, for example with a PIN, when it was added. Passkey sign-in requires user verification. If the key has none set up, the browser asks whoever holds the key to set it up, so a stolen key would be enough to sign in.
156
+
157
+ When a security key is added, the browser reports in the [`credProps` extension](https://www.w3.org/TR/webauthn-3/#sctn-authenticator-credential-properties-extension) whether it is discoverable. The gem stores this in `discoverable`. The registration options ask for `userVerification: "preferred"`, and the gem stores the signed UV flag in `uv_initialized`. `discoverable` is `false` when the browser does not report it. Both are `false` for security keys added before these columns existed. `PATCH /users/second_factor_webauthn_credentials/:id` promotes a security key only when both are `true`. Show the upgrade button only for those keys:
158
+ ```erb
159
+ <% if security_key.discoverable? && security_key.uv_initialized? %>
160
+ <%= button_to "Upgrade to passkey", second_factor_webauthn_credential_path(:user, security_key), method: :patch %>
161
+ <% end %>
162
+ ```
163
+
164
+ Security keys with user verification set up ask for it when they are added, but not at 2FA sign-in.
165
+
123
166
  #### 2FA Sign In with Security Keys
124
167
  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.
125
168
 
126
- The two factor authentication flow with WebAuthn works as follows:
169
+ In a browser, the two factor authentication flow with WebAuthn works as follows:
127
170
  1. User enters their primary credentials (e.g., email and password) and submits the form.
128
171
  2. If the user has 2FA enabled, they are redirected to a second factor authentication page.
129
172
  3. User clicks "Use security key", starting a WebAuthn authentication ceremony.
@@ -131,6 +174,95 @@ The two factor authentication flow with WebAuthn works as follows:
131
174
  5. User selects a credential and verifies with their [authenticator](https://www.w3.org/TR/webauthn-3/#webauthn-authenticator).
132
175
  6. The server verifies the response and signs in the user.
133
176
 
177
+ > [!NOTE]
178
+ > API clients are not redirected. Their password sign-in responds `401`, and they complete the second factor with JSON requests. See [Two-factor sign-in for API clients](#two-factor-sign-in-for-api-clients).
179
+
180
+ ## Challenge store
181
+
182
+ By default, WebAuthn challenges are kept in the session between the options request and the sign-in or registration request. To keep them in a cache instead:
183
+
184
+ ```ruby
185
+ # config/initializers/devise_webauthn.rb
186
+ Devise::Webauthn.challenge_store = :cache
187
+ # Optional. Defaults to Rails.cache and 5 minutes.
188
+ Devise::Webauthn::ChallengeStores::Cache.cache = Rails.cache
189
+ Devise::Webauthn::ChallengeStores::Cache.expires_in = 5.minutes
190
+ ```
191
+
192
+ Each challenge can be used once. The two requests can reach different servers or processes, so use a cache shared by all your servers (Redis, Memcached or Solid Cache). `ActiveSupport::Cache::MemoryStore` and `FileStore` are local to one process or host.
193
+
194
+ ## API clients and native apps
195
+
196
+ Mobile apps and other API clients can use passkeys and security keys without a session cookie. They authenticate each request with a token instead, for example with [devise-jwt](https://github.com/waiting-for-dev/devise-jwt).
197
+
198
+ ### Server setup
199
+
200
+ 1. **Keep challenges on the server.** The default challenge store keeps each challenge in the session. A client without a session cookie loses it between the options request and the next request. Use the `:cache` [challenge store](#challenge-store) with a cache shared by all your servers:
201
+ ```ruby
202
+ # config/initializers/devise_webauthn.rb
203
+ Devise::Webauthn.challenge_store = :cache
204
+ ```
205
+ 2. **Stop Devise from writing the user to the session.** Password, passkey and security key sign-in follow this setting:
206
+ ```ruby
207
+ # config/initializers/devise.rb
208
+ config.skip_session_storage = [:http_auth, :params_auth]
209
+ ```
210
+ If the same scope also signs in browsers, leave `:params_auth` out and set `request.env["devise.skip_storage"] = true` on your API requests. The gem reads it like Devise does, for that request only.
211
+ 3. **Respond with JSON.** Add the format to the controller Devise inherits from (`config.parent_controller`, `ApplicationController` by default). Send `Accept: application/json` from the client.
212
+ ```ruby
213
+ class ApplicationController < ActionController::Base
214
+ respond_to :html, :json
215
+ end
216
+ ```
217
+ - In an API-only app, inherit from `ActionController::API`, use `respond_to :json`, and set `config.navigational_formats = []` in the Devise initializer. Otherwise a request without an `Accept` header counts as a browser request, and Devise raises when it writes to the session.
218
+ - With `:registerable`, override `sign_up` in your registrations controller to call `sign_in(resource_name, resource, store: false)`. Devise's default writes to the session.
219
+ 4. **Accept your native apps.** Native apps do not have a browser origin. Tell WebAuthn which relying party and origins to accept:
220
+ ```ruby
221
+ WebAuthn.configure do |config|
222
+ config.rp_id = "example.com"
223
+ config.allowed_origins = [
224
+ "https://example.com", # web and iOS
225
+ "android:apk-key-hash:<base64url SHA-256 of your signing certificate>"
226
+ ]
227
+ end
228
+ ```
229
+ Your domain must also serve `/.well-known/apple-app-site-association` (with `webcredentials`) and `/.well-known/assetlinks.json` (with `delegate_permission/common.get_login_creds`).
230
+ 5. **With devise-jwt, issue a token after two-factor sign-in.** devise-jwt only issues a token on `POST /users/sign_in` by default. Add the two-factor path:
231
+ ```ruby
232
+ config.jwt do |jwt|
233
+ jwt.dispatch_requests = [["POST", %r{^/users/two_factor_authentication$}]]
234
+ end
235
+ ```
236
+
237
+ ### Endpoints
238
+
239
+ Send `public_key_credential` as the JSON object your WebAuthn library returns. Keep its `clientExtensionResults`: a security key can be promoted to a passkey only if they report it as discoverable. For a resource named `user`:
240
+
241
+ | Step | Request | Response |
242
+ |---|---|---|
243
+ | Sign-in options | `POST /users/passkey_authentication_options` | WebAuthn request options |
244
+ | Sign in | `POST /users/sign_in` with `public_key_credential` | `201`, and a JWT when you use devise-jwt |
245
+ | Registration options | `POST /users/passkey_registration_options` (authenticated) | WebAuthn creation options |
246
+ | Add passkey | `POST /users/passkeys` with `name` and `public_key_credential` (authenticated) | `201`, or `422` with `errors` |
247
+ | Delete passkey | `DELETE /users/passkeys/:id` (authenticated) | `204` |
248
+ | Security key registration options | `POST /users/security_key_registration_options` (authenticated) | WebAuthn creation options |
249
+ | Add security key | `POST /users/second_factor_webauthn_credentials` with `name` and `public_key_credential` (authenticated) | `201`, or `422` with `errors` |
250
+ | Promote security key to passkey | `PATCH /users/second_factor_webauthn_credentials/:id` (authenticated) | `204`, or `422` with `errors` unless the key is `discoverable` and `uv_initialized` |
251
+ | Delete security key | `DELETE /users/second_factor_webauthn_credentials/:id` (authenticated) | `204` |
252
+
253
+ ### Two-factor sign-in for API clients
254
+
255
+ When a user has 2FA enabled, password sign-in takes three requests:
256
+
257
+ 1. `POST /users/sign_in` with the email and password. The response is `401` with `error` and `two_factor_token`.
258
+ 2. `POST /users/security_key_authentication_options` with `two_factor_token`. The response has the WebAuthn request options.
259
+ 3. `POST /users/two_factor_authentication` with `two_factor_token` and `public_key_credential`. The response is `201`, and a JWT when you use devise-jwt.
260
+
261
+ About the `two_factor_token`:
262
+ - Send it in the request body. The gem ignores it in the query string, and adds it to `filter_parameters` so Rails does not log it.
263
+ - It expires after 5 minutes (`Devise::Webauthn::TwoFactorToken.expires_in`).
264
+ - The response includes it only when `skip_session_storage` includes `:params_auth`, or the request sets `devise.skip_storage`. Otherwise the session keeps the pending sign-in, and the client sends no token.
265
+
134
266
  ## Customization
135
267
 
136
268
  ### Customizing Views
@@ -273,6 +405,26 @@ devise_for :users, controllers: {
273
405
 
274
406
  3. Change or extend the generated controllers as needed.
275
407
 
408
+ The two-factor strategy is not one of the scope's default strategies. A two-factor controller that overrides `create` must run it by name, as `Devise::TwoFactorAuthenticationsController#create` does: `warden.authenticate!(:webauthn_two_factor_authenticatable, auth_options)`. Generated controllers call `super`, so they need no change.
409
+
410
+ ### Customizing the WebAuthn user name
411
+ When a passkey or a security key is added, the registration options send `webauthn_user_name` as both the WebAuthn `user.name` and `user.displayName`. A passkey keeps this name, and the browser or operating system shows it when the user picks a passkey to sign in.
412
+
413
+ By default it is the first authentication key with a non-nil value, such as the email. If that key is nil on a saved record, such as a plain `attr_accessor :login`, override `webauthn_user_name` in your model:
414
+ ```ruby
415
+ class User < ApplicationRecord
416
+ devise :database_authenticatable, :passkey_authenticatable, authentication_keys: [:login]
417
+
418
+ attr_accessor :login
419
+
420
+ def webauthn_user_name
421
+ username.presence || email
422
+ end
423
+ end
424
+ ```
425
+
426
+ The method must return a non-blank string. If it returns nil, the registration options have no `name` or `displayName`, `PublicKeyCredential.parseCreationOptionsFromJSON` throws a `TypeError` in the browser, and the user cannot add the passkey or security key.
427
+
276
428
  ### Manually implementing WebAuthn forms
277
429
 
278
430
  The gem provides two custom HTML elements for WebAuthn operations. While the [form helpers](#helper-methods) handle this automatically, you can use these elements directly for custom implementations.
@@ -329,6 +481,7 @@ Used for authenticating with existing credentials.
329
481
  ## Development
330
482
 
331
483
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rspec` to run the tests.
484
+ The API client tests run against an API-only app in `spec/internal_api`. Run them with `bundle exec rake spec:api`, or run both suites with `bundle exec rake`.
332
485
  To run the linter, use `bundle exec rubocop`.
333
486
 
334
487
  Before submitting a pull request, ensure that tests and linter pass.
data/Rakefile CHANGED
@@ -5,4 +5,9 @@ require "rspec/core/rake_task"
5
5
 
6
6
  RSpec::Core::RakeTask.new(:spec)
7
7
 
8
- task default: :spec
8
+ RSpec::Core::RakeTask.new("spec:api") do |task|
9
+ task.rspec_opts = "--options .rspec-api"
10
+ task.pattern = "spec/api/**/*_spec.rb"
11
+ end
12
+
13
+ task default: %i[spec spec:api]
@@ -2,7 +2,9 @@
2
2
 
3
3
  module Devise
4
4
  class PasskeyAuthenticationOptionsController < DeviseController
5
- skip_forgery_protection
5
+ include Devise::Webauthn::ChallengeStoreAccess
6
+
7
+ skip_forgery_protection if respond_to?(:skip_forgery_protection)
6
8
 
7
9
  def create
8
10
  passkey_options =
@@ -10,8 +12,7 @@ module Devise
10
12
  user_verification: "required"
11
13
  )
12
14
 
13
- # Store challenge in session for later verification
14
- session[:authentication_challenge] = passkey_options.challenge
15
+ challenge_store.write(:passkey_authentication, passkey_options.challenge)
15
16
 
16
17
  render json: passkey_options
17
18
  end
@@ -2,7 +2,9 @@
2
2
 
3
3
  module Devise
4
4
  class PasskeyRegistrationOptionsController < DeviseController
5
- skip_forgery_protection
5
+ include Devise::Webauthn::ChallengeStoreAccess
6
+
7
+ skip_forgery_protection if respond_to?(:skip_forgery_protection)
6
8
 
7
9
  before_action :authenticate_scope!
8
10
  before_action :ensure_webauthn_id!
@@ -12,17 +14,17 @@ module Devise
12
14
  WebAuthn::Credential.options_for_create(
13
15
  user: {
14
16
  id: resource.webauthn_id,
15
- name: resource_human_palatable_identifier
17
+ name: resource.webauthn_user_name
16
18
  },
17
19
  exclude: resource.passkeys.pluck(:external_id),
18
20
  authenticator_selection: {
19
21
  resident_key: "required",
22
+ require_resident_key: true,
20
23
  user_verification: "required"
21
24
  }
22
25
  )
23
26
 
24
- # Store challenge in session for later verification
25
- session[:webauthn_challenge] = passkey_options.challenge
27
+ challenge_store.write(:passkey_registration, passkey_options.challenge)
26
28
 
27
29
  render json: passkey_options
28
30
  end
@@ -37,12 +39,5 @@ module Devise
37
39
  def ensure_webauthn_id!
38
40
  resource.ensure_webauthn_id!
39
41
  end
40
-
41
- def resource_human_palatable_identifier
42
- authentication_keys = resource.class.authentication_keys
43
- authentication_keys = authentication_keys.keys if authentication_keys.is_a?(Hash)
44
-
45
- authentication_keys.filter_map { |authentication_key| resource.public_send(authentication_key) }.first
46
- end
47
42
  end
48
43
  end
@@ -2,35 +2,41 @@
2
2
 
3
3
  module Devise
4
4
  class PasskeysController < DeviseController
5
+ include Devise::Webauthn::ChallengeStoreAccess
6
+ include Devise::Webauthn::PublicKeyCredentialParam
7
+ include Devise::Webauthn::CredentialProperties
8
+
5
9
  before_action :authenticate_scope!
6
10
 
7
11
  def new; end
8
12
 
9
13
  def create
10
- passkey_from_params = WebAuthn::Credential.from_create(JSON.parse(params[:public_key_credential]))
11
- passkey = verify_and_save_passkey(passkey_from_params)
14
+ passkey = verify_and_save_passkey(public_key_credential_param)
12
15
 
13
16
  if passkey.persisted?
14
17
  set_flash_message! :notice, :passkey_created
15
18
  else
16
19
  set_flash_message! :alert, :passkey_verification_failed, scope: :"devise.failure"
17
20
  end
18
- redirect_to after_update_path
19
- rescue WebAuthn::Error
20
- set_flash_message! :alert, :passkey_verification_failed, scope: :"devise.failure"
21
- redirect_to after_update_path
21
+ if passkey.persisted? && !is_navigational_format?
22
+ head :created
23
+ else
24
+ # The responder calls the location lambda only when the passkey has no errors.
25
+ respond_with_navigational(passkey, location: -> { after_update_path }) { redirect_to after_update_path }
26
+ end
22
27
  ensure
23
- session.delete(:webauthn_challenge)
28
+ challenge_store.consume(:passkey_registration)
24
29
  end
25
30
 
26
31
  def destroy
27
- if resource.passkeys.destroy(params[:id])
32
+ passkey = resource.passkeys.find(params[:id])
33
+
34
+ if passkey.destroy
28
35
  set_flash_message! :notice, :passkey_deleted
29
36
  else
30
37
  set_flash_message! :alert, :passkey_deletion_failed, scope: :"devise.failure"
31
38
  end
32
-
33
- redirect_to after_update_path
39
+ respond_with_navigational(passkey) { redirect_to after_update_path }
34
40
  end
35
41
 
36
42
  private
@@ -40,18 +46,27 @@ module Devise
40
46
  self.resource = send(:"current_#{resource_name}")
41
47
  end
42
48
 
43
- def verify_and_save_passkey(passkey_from_params)
49
+ def verify_and_save_passkey(public_key_credential)
50
+ return passkey_with_verification_error if public_key_credential.nil?
51
+
52
+ passkey_from_params = WebAuthn::Credential.from_create(public_key_credential)
44
53
  passkey_from_params.verify(
45
- session[:webauthn_challenge],
54
+ challenge_store.consume(:passkey_registration),
46
55
  user_verification: true
47
56
  )
48
57
 
49
58
  resource.passkeys.create(
50
- external_id: passkey_from_params.id,
51
59
  name: params[:name],
52
- public_key: passkey_from_params.public_key,
53
- sign_count: passkey_from_params.sign_count
60
+ **credential_record_attributes(passkey_from_params, discoverable: true)
54
61
  )
62
+ rescue WebAuthn::Error
63
+ passkey_with_verification_error
64
+ end
65
+
66
+ def passkey_with_verification_error
67
+ passkey = WebauthnCredential.new
68
+ passkey.errors.add(:base, find_message(:passkey_verification_failed, scope: :"devise.failure"))
69
+ passkey
55
70
  end
56
71
 
57
72
  # The default url to be used after creating a passkey. You can overwrite
@@ -2,45 +2,53 @@
2
2
 
3
3
  module Devise
4
4
  class SecondFactorWebauthnCredentialsController < DeviseController
5
+ include Devise::Webauthn::ChallengeStoreAccess
6
+ include Devise::Webauthn::PublicKeyCredentialParam
7
+ include Devise::Webauthn::CredentialProperties
8
+
5
9
  before_action :authenticate_scope!
6
10
 
7
11
  def new; end
8
12
 
9
13
  def create
10
- security_key_from_params = WebAuthn::Credential.from_create(JSON.parse(params[:public_key_credential]))
11
- security_key = verify_and_save_security_key(security_key_from_params)
14
+ security_key = verify_and_save_security_key(public_key_credential_param)
12
15
 
13
16
  if security_key.persisted?
14
17
  set_flash_message! :notice, :security_key_created
15
18
  else
16
19
  set_flash_message! :alert, :webauthn_credential_verification_failed, scope: :"devise.failure"
17
20
  end
18
- redirect_to after_create_path
19
- rescue WebAuthn::Error
20
- set_flash_message! :alert, :webauthn_credential_verification_failed, scope: :"devise.failure"
21
- redirect_to after_create_path
21
+ if security_key.persisted? && !is_navigational_format?
22
+ head :created
23
+ else
24
+ # The responder calls the location lambda only when the security key has no errors.
25
+ respond_with_navigational(security_key, location: -> { after_create_path }) { redirect_to after_create_path }
26
+ end
22
27
  ensure
23
- session.delete(:webauthn_challenge)
28
+ challenge_store.consume(:security_key_registration)
24
29
  end
25
30
 
26
31
  def update
27
- if resource.second_factor_webauthn_credentials.find(params[:id]).update(authentication_factor: 0)
32
+ security_key = resource.second_factor_webauthn_credentials.find(params[:id])
33
+
34
+ if promotable?(security_key) && security_key.update(authentication_factor: 0)
28
35
  set_flash_message! :notice, :security_key_promoted
29
36
  else
37
+ add_security_key_promotion_error(security_key)
30
38
  set_flash_message! :alert, :security_key_promotion_failed, scope: :"devise.failure"
31
39
  end
32
-
33
- redirect_to after_update_path
40
+ respond_with_navigational(security_key) { redirect_to after_update_path }
34
41
  end
35
42
 
36
43
  def destroy
37
- if resource.second_factor_webauthn_credentials.destroy(params[:id])
44
+ security_key = resource.second_factor_webauthn_credentials.find(params[:id])
45
+
46
+ if security_key.destroy
38
47
  set_flash_message! :notice, :security_key_deleted
39
48
  else
40
49
  set_flash_message! :alert, :security_key_deletion_failed, scope: :"devise.failure"
41
50
  end
42
-
43
- redirect_to after_destroy_path
51
+ respond_with_navigational(security_key) { redirect_to after_destroy_path }
44
52
  end
45
53
 
46
54
  private
@@ -50,17 +58,36 @@ module Devise
50
58
  self.resource = send(:"current_#{resource_name}")
51
59
  end
52
60
 
53
- def verify_and_save_security_key(security_key_from_params)
61
+ def verify_and_save_security_key(public_key_credential)
62
+ return security_key_with_verification_error if public_key_credential.nil?
63
+
64
+ security_key_from_params = WebAuthn::Credential.from_create(public_key_credential)
54
65
  security_key_from_params.verify(
55
- session[:webauthn_challenge]
66
+ challenge_store.consume(:security_key_registration)
56
67
  )
57
68
 
58
69
  resource.second_factor_webauthn_credentials.create(
59
- external_id: security_key_from_params.id,
60
70
  name: params[:name],
61
- public_key: security_key_from_params.public_key,
62
- sign_count: security_key_from_params.sign_count
71
+ **credential_record_attributes(security_key_from_params)
63
72
  )
73
+ rescue WebAuthn::Error
74
+ security_key_with_verification_error
75
+ end
76
+
77
+ # Passkey sign-in requires user verification. A key that did not verify the user when it was
78
+ # added may have none set up, and the browser would let whoever holds it set it up.
79
+ def promotable?(security_key)
80
+ security_key.discoverable? && security_key.uv_initialized?
81
+ end
82
+
83
+ def add_security_key_promotion_error(security_key)
84
+ security_key.errors.add(:base, find_message(:security_key_promotion_failed, scope: :"devise.failure"))
85
+ end
86
+
87
+ def security_key_with_verification_error
88
+ security_key = WebauthnCredential.new
89
+ security_key.errors.add(:base, find_message(:webauthn_credential_verification_failed, scope: :"devise.failure"))
90
+ security_key
64
91
  end
65
92
 
66
93
  # The default url to be used after creating a second factor key. You can overwrite
@@ -2,7 +2,10 @@
2
2
 
3
3
  module Devise
4
4
  class SecurityKeyAuthenticationOptionsController < DeviseController
5
- skip_forgery_protection
5
+ include Devise::Webauthn::ChallengeStoreAccess
6
+ include Devise::Webauthn::PendingTwoFactorSignIn
7
+
8
+ skip_forgery_protection if respond_to?(:skip_forgery_protection)
6
9
 
7
10
  before_action :set_resource
8
11
 
@@ -13,8 +16,7 @@ module Devise
13
16
  user_verification: "discouraged"
14
17
  )
15
18
 
16
- # Store challenge in session for later verification
17
- session[:two_factor_authentication_challenge] = security_key_authentication_options.challenge
19
+ challenge_store.write(:two_factor_authentication, security_key_authentication_options.challenge)
18
20
 
19
21
  render json: security_key_authentication_options
20
22
  end
@@ -22,7 +24,10 @@ module Devise
22
24
  private
23
25
 
24
26
  def set_resource
25
- @resource = resource_class.find(session[:current_authentication_resource_id])
27
+ sign_in_attempt = two_factor_sign_in_attempt_for(resource_name)
28
+ throw :warden, scope: resource_name, message: :sign_in_not_initiated if sign_in_attempt.blank?
29
+
30
+ @resource = resource_class.find(sign_in_attempt["id"])
26
31
  end
27
32
  end
28
33
  end