Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Allow passkeys to satisfy 2FA on `/session/2fa` (#39674)

Rafael dos Santos Silva99ce75a01ccb
diff --git a/app/controllers/session_controller.rb b/app/controllers/session_controller.rb
index 13769ebcb36..a697f4d7402 100644
--- a/app/controllers/session_controller.rb
+++ b/app/controllers/session_controller.rb
@@ -534,12 +534,21 @@ class SessionController < ApplicationController
backup_enabled: user.backup_codes_enabled?,
allowed_methods: challenge[:allowed_methods],
)
- if user.security_keys_enabled?
+ passkeys_for_2fa = user.passkeys_for_2fa_enabled?
+ if user.security_keys_enabled? || passkeys_for_2fa
DiscourseWebauthn.stage_challenge(user, server_session)
- json.merge!(DiscourseWebauthn.allowed_credentials(user, server_session))
- json[:security_keys_enabled] = true
+ json.merge!(
+ DiscourseWebauthn.allowed_credentials(
+ user,
+ server_session,
+ include_passkeys: passkeys_for_2fa,
+ ),
+ )
+ json[:security_keys_enabled] = user.security_keys_enabled?
+ json[:passkeys_enabled] = passkeys_for_2fa
else
json[:security_keys_enabled] = false
+ json[:passkeys_enabled] = false
end
json[:description] = challenge[:description] if challenge[:description]
else
diff --git a/app/models/concerns/second_factor_manager.rb b/app/models/concerns/second_factor_manager.rb
index 438b9e66eb9..cd92db95e72 100644
--- a/app/models/concerns/second_factor_manager.rb
+++ b/app/models/concerns/second_factor_manager.rb
@@ -80,6 +80,16 @@ module SecondFactorManager
&.exists?
end
+ def passkeys_for_2fa_enabled?
+ SiteSetting.allow_passkeys_for_2fa && SiteSetting.enable_passkeys &&
+ !SiteSetting.enable_discourse_connect && SiteSetting.enable_local_logins &&
+ self.security_keys&.where(factor_type: UserSecurityKey.factor_types[:first_factor])&.exists?
+ end
+
+ # Passkey-as-2FA (`passkeys_for_2fa_enabled?`) is intentionally excluded:
+ # it only satisfies `/session/2fa`. Password login, email login, and password
+ # reset have no passkey UI yet, so counting passkeys here would make those
+ # flows skip 2FA for passkey-only users.
def has_any_second_factor_methods_enabled?
totp_enabled? || security_keys_enabled?
end
@@ -106,7 +116,10 @@ module SecondFactorManager
def authenticate_second_factor(params, server_session)
ok_result = SecondFactorAuthenticationResult.new(true)
- return ok_result if !security_keys_enabled? && !totp_or_backup_codes_enabled?
+ if !security_keys_enabled? && !totp_or_backup_codes_enabled? &&
+ (!passkeys_for_2fa_enabled? || params[:second_factor_method].blank?)
+ return ok_result
+ end
second_factor_token = params[:second_factor_token]
second_factor_method = params[:second_factor_method]&.to_i
@@ -157,17 +170,20 @@ module SecondFactorManager
when UserSecondFactor.methods[:backup_codes]
return backup_codes_enabled?
when UserSecondFactor.methods[:security_key]
- return security_keys_enabled?
+ return security_keys_enabled? || passkeys_for_2fa_enabled?
end
false
end
def authenticate_security_key(server_session, security_key_credential)
+ factor_types = [UserSecurityKey.factor_types[:second_factor]]
+ factor_types << UserSecurityKey.factor_types[:first_factor] if passkeys_for_2fa_enabled?
+
::DiscourseWebauthn::AuthenticationService.new(
self,
security_key_credential,
session: server_session,
- factor_type: UserSecurityKey.factor_types[:second_factor],
+ factor_type: factor_types,
).authenticate_security_key
end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 39859aa8653..3f8d912b4ca 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -2857,8 +2857,10 @@ en:
second_factor_backup_description: "Please enter one of your backup codes:"
second_factor: "Log in using Authenticator app"
security_key_description: "When you have your physical security key or compatible mobile device prepared press the Authenticate with Security Key button below."
+ security_key_or_passkey_description: "When you have your security key, passkey, or compatible mobile device prepared press the button below."
security_key_alternative: "Try another way"
security_key_authenticate: "Authenticate with Security Key"
+ security_key_or_passkey_authenticate: "Authenticate with security key or passkey"
security_key_not_allowed_error: "The security key authentication process either timed out or was cancelled."
security_key_no_matching_credential_error: "No matching credentials could be found in the provided security key."
security_key_support_missing_error: "Your current device or browser does not support the use of security keys. Please use a different method."
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index eb764c579d9..53f75437a92 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -2054,6 +2054,7 @@ en:
enable_local_logins: "Enable local username and password login based accounts. WARNING: if disabled, you may be unable to log in if you have not previously configured at least one alternate login method."
enable_local_logins_via_email: "Allow users to request a one-click login link to be sent to them via email."
+ allow_passkeys_for_2fa: "Allow users to use a passkey to satisfy two-factor authentication when confirming a sensitive action."
allow_new_registrations: "Allow new user registrations. Uncheck this to prevent anyone from creating a new account."
enable_signup_cta: "Show a notice to returning anonymous users prompting them to sign up for an account."
enable_discourse_id: "Enable authentication via Discourse ID, a single sign-on service that allows users to log in to multiple Discourse sites using a single account. Common social login providers like Google, Facebook, Apple, and GitHub are supported without additional configuration. See <a href='https://id.discourse.com' target='_blank'>id.discourse.com</a> for more details."
diff --git a/config/site_settings.yml b/config/site_settings.yml
index c80d1d3e127..cc8a4178216 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -653,6 +653,10 @@ login:
client: true
default: true
hidden: true
+ allow_passkeys_for_2fa:
+ client: true
+ default: false
+ area: "login"
allow_new_registrations:
client: true
default: true
diff --git a/frontend/discourse/app/controllers/second-factor-auth.js b/frontend/discourse/app/controllers/second-factor-auth.js
index 148405598ca..e29af39d466 100644
--- a/frontend/discourse/app/controllers/second-factor-auth.js
+++ b/frontend/discourse/app/controllers/second-factor-auth.js
@@ -31,9 +31,21 @@ export default class SecondFactorAuthController extends Controller {
return this.model?.backup_enabled;
}
- @computed("model.security_keys_enabled")
+ @computed("model.security_keys_enabled", "model.passkeys_enabled")
get securityKeysEnabled() {
- return this.model?.security_keys_enabled;
+ return this.model?.security_keys_enabled || this.model?.passkeys_enabled;
+ }
+
+ @computed("model.passkeys_enabled")
+ get passkeysEnabled() {
+ return this.model?.passkeys_enabled;
+ }
+
+ @computed("passkeysEnabled")
+ get securityKeyAuthenticateLabel() {
+ return this.passkeysEnabled
+ ? "login.security_key_or_passkey_authenticate"
+ : "login.security_key_authenticate";
}
@computed("model.allowed_methods")
@@ -153,13 +165,15 @@ export default class SecondFactorAuthController extends Controller {
}
}
- @computed("shownSecondFactorMethod")
+ @computed("shownSecondFactorMethod", "passkeysEnabled")
get secondFactorDescription() {
switch (this.shownSecondFactorMethod) {
case TOTP:
return i18n("login.second_factor_description");
case SECURITY_KEY:
- return i18n("login.security_key_description");
+ return this.passkeysEnabled
+ ? i18n("login.security_key_or_passkey_description")
+ : i18n("login.security_key_description");
case BACKUP_CODE:
return i18n("login.second_factor_backup_description");
}
@@ -189,6 +203,14 @@ export default class SecondFactorAuthController extends Controller {
this.set("secondFactorToken", null);
this.set("userSelectedMethod", null);
this.set("loadError", false);
+ this.set("autoTriggeredPasskey", false);
+ }
+
+ maybeAutoTriggerPasskey() {
+ if (this.passkeysEnabled && !this.autoTriggeredPasskey) {
+ this.set("autoTriggeredPasskey", true);
+ this.authenticateSecurityKey({ silent: true });
+ }
}
displayError(message) {
@@ -241,7 +263,8 @@ export default class SecondFactorAuthController extends Controller {
}
@action
- authenticateSecurityKey() {
+ authenticateSecurityKey(options = {}) {
+ const silent = options?.silent === true;
getWebauthnCredential(
this.model.challenge,
this.model.allowed_credential_ids,
@@ -249,8 +272,11 @@ export default class SecondFactorAuthController extends Controller {
this.verifySecondFactor({ second_factor_token: credentialData });
},
(errorMessage) => {
- this.displayError(errorMessage);
- }
+ if (!silent) {
+ this.displayError(errorMessage);
+ }
+ },
+ { userVerification: this.passkeysEnabled ? "preferred" : "discouraged" }
);
}
diff --git a/frontend/discourse/app/lib/webauthn.js b/frontend/discourse/app/lib/webauthn.js
index 08c61c7d130..e0d0e83a67b 100644
--- a/frontend/discourse/app/lib/webauthn.js
+++ b/frontend/discourse/app/lib/webauthn.js
@@ -43,7 +43,8 @@ export function getWebauthnCredential(
challenge,
allowedCredentialIds,
successCallback,
- errorCallback
+ errorCallback,
+ { userVerification = "discouraged" } = {}
) {
if (!isWebauthnSupported()) {
return errorCallback(i18n("login.security_key_support_missing_error"));
@@ -66,10 +67,10 @@ export function getWebauthnCredential(
challenge: challengeBuffer,
allowCredentials,
timeout: 60000, // this is just a hint
- // in the backend, we don't check for user verification for 2FA
- // therefore we should indicate to browser that it's not necessary
- // (this is only a hint, though, browser may still prompt)
- userVerification: "discouraged",
+ // "discouraged" for plain 2FA (security keys), "preferred" when passkeys
+ // may be present so the browser prompts for UV on passkey credentials
+ // while still allowing non-UV security keys.
+ userVerification,
},
signal: WebauthnAbortHandler.signal(),
})
diff --git a/frontend/discourse/app/routes/second-factor-auth.js b/frontend/discourse/app/routes/second-factor-auth.js
index 98f5229b15d..55288dd6fec 100644
--- a/frontend/discourse/app/routes/second-factor-auth.js
+++ b/frontend/discourse/app/routes/second-factor-auth.js
@@ -33,6 +33,8 @@ export default class SecondFactorAuth extends DiscourseRoute {
if (model.error) {
controller.displayError(model.error);
controller.set("loadError", true);
+ } else {
+ controller.maybeAutoTriggerPasskey();
}
}
}
diff --git a/frontend/discourse/app/templates/second-factor-auth.gjs b/frontend/discourse/app/templates/second-factor-auth.gjs
index bb7db1f97b6..b14aeb06fa6 100644
--- a/frontend/discourse/app/templates/second-factor-auth.gjs
+++ b/frontend/discourse/app/templates/second-factor-auth.gjs
@@ -23,7 +23,7 @@ export default <template>
<DButton
@action={{@controller.authenticateSecurityKey}}
@icon="key"
- @label="login.security_key_authenticate"
+ @label={{@controller.securityKeyAuthenticateLabel}}
id="security-key-authenticate-button"
class="btn-large btn-primary"
/>
diff --git a/lib/discourse_webauthn.rb b/lib/discourse_webauthn.rb
index 962464aabda..73137076be9 100644
--- a/lib/discourse_webauthn.rb
+++ b/lib/discourse_webauthn.rb
@@ -92,13 +92,16 @@ module DiscourseWebauthn
server_session.delete(session_challenge_key(user))
end
- def self.allowed_credentials(user, server_session)
- return {} if !user.security_keys_enabled?
+ def self.allowed_credentials(user, server_session, include_passkeys: false)
+ has_security_keys = user.security_keys_enabled?
+ has_passkeys = include_passkeys && user.passkeys_for_2fa_enabled?
+ return {} if !has_security_keys && !has_passkeys
- {
- allowed_credential_ids: user.second_factor_security_key_credential_ids,
- challenge: challenge(user, server_session),
- }
+ credential_ids = []
+ credential_ids.concat(user.second_factor_security_key_credential_ids) if has_security_keys
+ credential_ids.concat(user.passkey_credential_ids) if has_passkeys
+
+ { allowed_credential_ids: credential_ids, challenge: challenge(user, server_session) }
end
def self.challenge(user, server_session)
diff --git a/lib/discourse_webauthn/authentication_service.rb b/lib/discourse_webauthn/authentication_service.rb
index 1fc5b42e236..bc6a6cd848b 100644
--- a/lib/discourse_webauthn/authentication_service.rb
+++ b/lib/discourse_webauthn/authentication_service.rb
@@ -17,24 +17,31 @@ module DiscourseWebauthn
end
# 6. Identify the user being authenticated and verify that this user is the
- # owner of the public key credential source credentialSource identified by credential.id:
-
- # 6a. If the user was identified before the authentication ceremony was initiated,
- # verify that the identified user account contains a credential record whose id equals credential.rawId.
- security_key = UserSecurityKey.find_by(credential_id: @params[:credentialId])
+ # owner of the public key credential source credentialSource identified by credential.id.
+ # Disabled credentials must be rejected even if a row still exists in the database;
+ # advertised allow-lists already exclude them, but the lookup here must enforce it too.
+ security_key = UserSecurityKey.find_by(credential_id: @params[:credentialId], enabled: true)
raise(KeyNotFoundError, I18n.t("webauthn.validation.not_found_error")) if security_key.blank?
- if @factor_type == UserSecurityKey.factor_types[:second_factor] &&
- (@current_user == nil || security_key.user == nil || security_key.user != @current_user)
+ accepted_factor_types = Array(@factor_type)
+ if accepted_factor_types.exclude?(security_key.factor_type)
raise(OwnershipError, I18n.t("webauthn.validation.ownership_error"))
end
- # 6b. If the user was not identified before the authentication ceremony was initiated,
- # verify that response.userHandle is present. Verify that the user account identified by response.userHandle
- # contains a credential record whose id equals credential.rawId
- if @factor_type == UserSecurityKey.factor_types[:first_factor] &&
- Base64.decode64(@params[:userHandle]) != security_key.user.secure_identifier
- raise(OwnershipError, I18n.t("webauthn.validation.ownership_error"))
+ if @current_user
+ # 6a. If the user was identified before the authentication ceremony was initiated,
+ # verify that the identified user account contains a credential record whose id equals credential.rawId.
+ if security_key.user_id != @current_user.id
+ raise(OwnershipError, I18n.t("webauthn.validation.ownership_error"))
+ end
+ else
+ # 6b. If the user was not identified before the authentication ceremony was initiated,
+ # verify that response.userHandle is present. Verify that the user account identified by response.userHandle
+ # contains a credential record whose id equals credential.rawId
+ if @params[:userHandle].blank? ||
+ Base64.decode64(@params[:userHandle]) != security_key.user.secure_identifier
+ raise(OwnershipError, I18n.t("webauthn.validation.ownership_error"))
+ end
end
# 7. No upstream step
@@ -72,7 +79,7 @@ module DiscourseWebauthn
# User verification SHOULD be required if, and only if, options.userVerification is set to required.
# If user verification was determined to be required, verify that the UV bit of the flags in authData is set.
# Otherwise, ignore the value of the UV flag.
- validate_user_verification if @factor_type == UserSecurityKey.factor_types[:first_factor]
+ validate_user_verification if security_key.first_factor?
# 19. If the BE bit of the flags in authData is not set, verify that the BS bit is not set.
# Not using this right now.
diff --git a/spec/lib/concern/second_factor_manager_spec.rb b/spec/lib/concern/second_factor_manager_spec.rb
index 765a538d5cc..201d18ad2af 100644
--- a/spec/lib/concern/second_factor_manager_spec.rb
+++ b/spec/lib/concern/second_factor_manager_spec.rb
@@ -163,6 +163,27 @@ RSpec.describe SecondFactorManager do
end
end
+ describe "#passkeys_for_2fa_enabled?" do
+ before do
+ SiteSetting.allow_passkeys_for_2fa = true
+ Fabricate(:passkey_with_random_credential, user: user)
+ end
+
+ it "is true when both setting flags are on" do
+ expect(user.passkeys_for_2fa_enabled?).to eq(true)
+ end
+
+ it "is false when the global enable_passkeys kill switch is off" do
+ SiteSetting.enable_passkeys = false
+ expect(user.passkeys_for_2fa_enabled?).to eq(false)
+ end
+
+ it "is false when allow_passkeys_for_2fa is off" do
+ SiteSetting.allow_passkeys_for_2fa = false
+ expect(user.passkeys_for_2fa_enabled?).to eq(false)
+ end
+ end
+
describe "#authenticate_second_factor" do
let(:params) { {} }
let(:server_session) { ServerSession.new("some-prefix") }
@@ -177,6 +198,32 @@ RSpec.describe SecondFactorManager do
it "keeps used_2fa_method nil because no authentication is done" do
expect(user.authenticate_second_factor(params, server_session).used_2fa_method).to eq(nil)
end
+
+ context "when the user has a passkey and allow_passkeys_for_2fa is enabled" do
+ # Login / email-login / password-reset flows call authenticate_second_factor
+ # without a second_factor_method. They don't advertise passkeys, so a
+ # passkey-only user must still pass through these flows; only the explicit
+ # 2FA endpoint (which submits a method) should require passkey validation.
+ before do
+ SiteSetting.allow_passkeys_for_2fa = true
+ Fabricate(:passkey_with_random_credential, user: user)
+ end
+
+ it "returns OK when no second_factor_method is submitted" do
+ expect(user.authenticate_second_factor(params, server_session).ok).to eq(true)
+ end
+
+ it "validates the credential when a method is submitted" do
+ params_with_method = {
+ second_factor_method: UserSecondFactor.methods[:security_key],
+ second_factor_token: {
+ credentialId: "missing",
+ },
+ }
+ result = user.authenticate_second_factor(params_with_method, server_session)
+ expect(result.ok).to eq(false)
+ end
+ end
end
context "when only security key is enabled" do
diff --git a/spec/lib/discourse_webauthn/authentication_service_spec.rb b/spec/lib/discourse_webauthn/authentication_service_spec.rb
index 47fcb38e33d..1956bc740be 100644
--- a/spec/lib/discourse_webauthn/authentication_service_spec.rb
+++ b/spec/lib/discourse_webauthn/authentication_service_spec.rb
@@ -272,6 +272,11 @@ RSpec.describe DiscourseWebauthn::AuthenticationService do
end
describe "authenticating passkeys" do
+ # Passkey login is initiated without a current_user — the user is identified
+ # via userHandle in the response. This matches the production call site at
+ # SessionController#passkey_login.
+ let(:current_user) { nil }
+ let(:security_key_user) { Fabricate(:user) }
let(:options) do
{ factor_type: UserSecurityKey.factor_types[:first_factor], session: server_session }
end
diff --git a/spec/requests/session_controller_spec.rb b/spec/requests/session_controller_spec.rb
index 13ebad157e5..9cf6e3e4e65 100644
--- a/spec/requests/session_controller_spec.rb
+++ b/spec/requests/session_controller_spec.rb
@@ -3057,6 +3057,7 @@ RSpec.describe SessionController do
expect(challenge_data["totp_enabled"]).to eq(true)
expect(challenge_data["backup_enabled"]).to eq(false)
expect(challenge_data["security_keys_enabled"]).to eq(false)
+ expect(challenge_data["passkeys_enabled"]).to eq(false)
expect(challenge_data["allowed_methods"]).to contain_exactly(
UserSecondFactor.methods[:totp],
UserSecondFactor.methods[:security_key],
@@ -3087,6 +3088,52 @@ RSpec.describe SessionController do
UserSecondFactor.methods[:backup_codes],
)
end
+
+ context "when the user has a passkey and allow_passkeys_for_2fa is enabled" do
+ before { SiteSetting.allow_passkeys_for_2fa = true }
+
+ let!(:passkey) do
+ Fabricate(
+ :user_security_key,
+ user: user,
+ credential_id: valid_passkey_data[:credential_id],
+ public_key: valid_passkey_data[:public_key],
+ factor_type: UserSecurityKey.factor_types[:first_factor],
+ )
+ end
+
+ it "exposes the passkey credentials and a webauthn challenge" do
+ post "/session/2fa/test-action", xhr: true
+ nonce = response.parsed_body["second_factor_challenge_nonce"]
+ get "/session/2fa.json", params: { nonce: nonce }
+
+ expect(response.status).to eq(200)
+ challenge_data = response.parsed_body
+ expect(challenge_data["passkeys_enabled"]).to eq(true)
+ expect(challenge_data["security_keys_enabled"]).to eq(false)
+ expect(challenge_data["allowed_credential_ids"]).to include(
+ valid_passkey_data[:credential_id],
+ )
+ expect(challenge_data["challenge"]).to be_present
+ end
+ end
+
+ context "when the user has a passkey and allow_passkeys_for_2fa is disabled" do
+ before { SiteSetting.allow_passkeys_for_2fa = false }
+
+ let!(:passkey) { Fabricate(:passkey_with_random_credential, user: user) }
+
+ it "does not expose the passkey" do
+ post "/session/2fa/test-action", xhr: true
+ nonce = response.parsed_body["second_factor_challenge_nonce"]
+ get "/session/2fa.json", params: { nonce: nonce }
+
+ expect(response.status).to eq(200)
+ challenge_data = response.parsed_body
+ expect(challenge_data["passkeys_enabled"]).to eq(false)
+ expect(challenge_data["allowed_credential_ids"]).to be_blank
+ end
+ end
end
end
@@ -3213,6 +3260,78 @@ RSpec.describe SessionController do
post "/session/2fa/test-action", params: { second_factor_nonce: nonce }
expect(response.status).to eq(401)
end
+
+ context "with a passkey credential" do
+ let!(:passkey) do
+ Fabricate(
+ :user_security_key,
+ user: user,
+ credential_id: valid_passkey_data[:credential_id],
+ public_key: valid_passkey_data[:public_key],
+ factor_type: UserSecurityKey.factor_types[:first_factor],
+ )
+ end
+
+ before do
+ user.create_or_fetch_secure_identifier
+ DiscourseWebauthn.stubs(:origin).returns("http://localhost:3000")
+ end
+
+ it "satisfies 2fa when allow_passkeys_for_2fa is enabled" do
+ SiteSetting.allow_passkeys_for_2fa = true
+ simulate_localhost_passkey_challenge
+
+ post "/session/2fa/test-action", xhr: true
+ nonce = response.parsed_body["second_factor_challenge_nonce"]
+
+ post "/session/2fa.json",
+ params: {
+ nonce: nonce,
+ second_factor_method: UserSecondFactor.methods[:security_key],
+ second_factor_token: valid_passkey_auth_data,
+ }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["ok"]).to eq(true)
+ end
+
+ it "is rejected when allow_passkeys_for_2fa is disabled" do
+ SiteSetting.allow_passkeys_for_2fa = false
+ simulate_localhost_passkey_challenge
+
+ post "/session/2fa/test-action", xhr: true
+ nonce = response.parsed_body["second_factor_challenge_nonce"]
+
+ post "/session/2fa.json",
+ params: {
+ nonce: nonce,
+ second_factor_method: UserSecondFactor.methods[:security_key],
+ second_factor_token: valid_passkey_auth_data,
+ }
+
+ expect(response.status).to eq(403)
+ end
+
+ it "rejects an assertion from a disabled passkey even when the user has another enabled passkey" do
+ SiteSetting.allow_passkeys_for_2fa = true
+ simulate_localhost_passkey_challenge
+ passkey.update!(enabled: false)
+ Fabricate(:passkey_with_random_credential, user: user)
+
+ post "/session/2fa/test-action", xhr: true
+ nonce = response.parsed_body["second_factor_challenge_nonce"]
+
+ post "/session/2fa.json",
+ params: {
+ nonce: nonce,
+ second_factor_method: UserSecondFactor.methods[:security_key],
+ second_factor_token: valid_passkey_auth_data,
+ }
+
+ expect(response.status).to eq(400)
+ expect(response.parsed_body["error"]).to eq(I18n.t("webauthn.validation.not_found_error"))
+ end
+ end
end
end