Account SecurityManaging Authenticators

Managing Authenticators

On this page

Introduction

A factor is a kind of sign-in method, such as an authenticator app or a passkey. An authenticator is one a user has set up. One set of routes adds, renames and removes authenticators for every factor, as in the PHP package. Turn them on with features.manage_authenticators:

Rust
config.section_mut::<laravel_keyring::KeyringConfig>().features.manage_authenticators = true;

Without it, users can't set up a sign-in method beyond their password. The rules for adding, removing and freezing are the PHP package's AuthenticatorChanges, so an account behaves the same on either side.

Email Verification

A user type that derives laravel-rust's MustVerifyEmail must verify its address before beginning or confirming an enrollment, as in the PHP package. Until it does, it gets a 403.

With features.registration on, anyone can type any address, so addresses have to be verified at all: the provider needs verify_emails() with features.email_verification on. Otherwise enrolling fails with a server error that says what to change, the PHP package's EmailVerificationRequired. Without registration, accounts come from you, so verification isn't required.

Who May Enroll

If you prove addresses another way, decide who may enroll yourself, with the provider's allow_enrollment_when():

Rust
KeyringServiceProvider::<Users>::new().allow_enrollment_when(|user: &User| user.approved_at.is_some());

It takes a closure of the user, or an AuthorizesEnrollment for a check that has to look something up. It replaces the verified-email rule. A user it refuses gets the same 403. laravel_keyring::allows_enrollment(&user) asks it from your own code.

Adding an Authenticator

Adding an authenticator takes two steps, as in the PHP package. Nothing is saved until the second one succeeds.

Beginning

POST /user/authenticators/{factor} starts an enrollment: a new base32 secret, algorithm, the otpauth:// url and the qr code as SVG for an authenticator app, the eight codes for recovery codes, options for navigator.credentials.create() for a passkey or security key (excluding every key the user has), or { "length", "sent": true } for a code factor, once its first code is sent. It's kept in the session for enrollments (15 minutes), encrypted, for the account that began it. Starting again replaces it, and signing in forgets it.

Beginning a code factor's enrollment is under the keyring limiter (limits.forms), where the PHP package doesn't limit it.

The Password for a First Second Factor

As in the PHP package: the first second factor of an account with an established password and no established second factor takes the password, typed when it begins (password) and checked under the password's rate limits. So does a code factor that's sent_to_an_address() there. A factor saved without it is marked added_without_password. See the PHP docs for why.

The password checked here dispatches Attempting and FactorVerified, as a challenge's answer does, besides the PHP package's FactorFailed, Lockout and AccountLocked. It doesn't run the pipeline.

Confirming

POST /user/authenticators/{factor}/confirm proves it works (code, nothing for recovery codes, credential, or a code factor's code, and an optional name) and saves it, once, whichever copy of the session it comes back in. The first sign-in method is the default. The first extra factor, or one added once the codes have run out, comes with recovery codes. Confirming counts the new method as verified in this session, which moves to a new session ID and record and raises its level.

Each change runs under the lock on the user, adding one only while the session that asked is still signed in. A key already registered to anyone isn't added again.

Recovery Codes

As in the PHP package: recovery codes need a factor to back up, new ones replace the old, and remaining and replace say when to make a new set. POST /user/authenticators/recovery then /confirm makes a set. See Recovery Codes.

Renaming and Choosing the Default

PATCH /user/authenticators/{factor} renames it (name) or makes it the default (default, never for recovery codes or a single sign-on link). The URL names the authenticator by its ID, under the {factor} parameter: laravel-rust's router takes one parameter name at a place in a path, so every authenticator route uses {factor}. The URLs are the PHP package's.

Removing Authenticators

DELETE /user/authenticators/{factor} removes the authenticator named by its ID. As in the PHP package, removing what would leave no way to sign in, or a policy without if_enrolled unmet, is refused (last_factor), and removing the last second factor takes the password, long enough to stand alone (passwords.min_without_mfa), and the recovery codes go with it. A removal or replacement stops trusting the user's devices, and forgets the failures in a row counted against what went.

Frozen Sign-In Methods

The freeze is the PHP package's: for authenticator_changes.established_after (7 days) after a factor that isn't established yet was added, or after something established was removed or replaced, removing, replacing or renaming an established authenticator, or recovery codes with codes left, is refused with a 422 on authenticator saying how long is left, and frozen { "reason": "new-authenticator" | "recent-change", "until", "skip" }. New ones can always go. The changes are kept in keyring_sign_in_changes. See the PHP docs for why.

Established Authenticators

An authenticator is established once the account has had it for authenticator_changes.established_after. UserKeyring::is_established() and established() say which are.

Making a Change With an Established Key

The owner can make one change anyway with an established key added before the session signed in, or an authenticator app, with authenticator_changes.skip_with_totp. POST /user/authenticators/{factor}/proof-options { "action": "remove" | "rename" | "replace", "target", "name" } answers options for that change alone, and the change's own request sends the answer as proof { "factor", "credential" } (or code, and authenticator for one of two apps). A challenge is answered once, in any copy of the session, and the change still freezes the account.

Getting Past the Freeze

As in the PHP docs: wait it out, make the change with an established key, or reset the password. Setting established_after to zero turns the freeze off.

Signing Out Other Sessions

Confirming an enrollment and removing an authenticator both take sign_out_others. When it's true and the change goes through, Keyring signs the user out everywhere else, as DELETE /user/sessions does.

From JavaScript

The browser package's helpers (enroll(), beginEnrollment(), confirmEnrollment(), renameAuthenticator(), makeDefault(), removeAuthenticator() and proveWithKey()) work with the crate unchanged, since the routes and JSON are the same. See the PHP docs and Frontend.

From PHP

From Rust, UserKeyring::of(&user) is the PHP package's $user->keyring:

Rust
use laravel_keyring::{Category, Requirement, UserKeyring}; let keyring = UserKeyring::of(&user).await?; keyring.all(); // every confirmed authenticator, default firstkeyring.default_authenticator(); // the default, or the first one a challenge can ask forkeyring.of_factor("security-key"); // one factor's authenticatorskeyring.find(&id);keyring.has(Category::Possession);keyring.can_meet(&requirement);keyring.has_second_factor();

It also has unregistered, has_factor_to_recover, has_recovery_codes, should_replace_recovery_codes, without_fallbacks, is_established, established, freshly_provable, reachable, can_confirm and can_sign_in, as the PHP package's methods. It's what the user's sign-in methods were when it was loaded: load it again after changing them, as refresh() does.

For a settings page, laravel_keyring::sign_in_methods(&user) gives what such a page shows, as a SignInMethods that serializes with camelCase keys:

Key
authenticators The user's authenticators, the password left out, each as the routes present one (factor, id, name, createdAt, lastUsedAt, and remaining, replace, hint, provider or email where the factor has them), with isDefault, and frozen when the freeze holds it.
enrollable The keys of the factors the user can add. Recovery codes only once the account has a factor for them to stand in for.
passwordToAdd The keys of those that take the current password to add.
frozen The freeze's reason, until (ISO 8601) and message, or null.
hasSecondFactor Whether the account has a second factor. Recovery codes and emailed codes don't count.

The user type implements ReceivesMail, as Keyring's does: an emailed code's hint masks its address. There's no Eloquent relationship: authenticators are rows in keyring_authenticators, with secret encrypted.

Routes

Method URI Does
POST /user/authenticators/{factor} Begins an enrollment. May check the password.
POST /user/authenticators/{factor}/confirm Finishes the enrollment.
POST /user/authenticators/{factor}/proof-options Returns the challenge for one change to a frozen account.
PATCH /user/authenticators/{factor} Renames the authenticator with that ID, or makes it the default.
DELETE /user/authenticators/{factor} Removes the authenticator with that ID.

Every route needs a signed-in user with a fresh verification within changes_fresh_for (15 minutes), and impersonating users are refused. The keyring limiter (limits.forms, six a minute) limits beginning, confirming, removing and the proof options, and the routes that change the session take its lock. Someone else's authenticator is the 404 a missing one gets, and goes on record (AccessRefused).

Responses

The status responses are the PHP package's: enrollment-started with factor and enrollment, authenticator-added with authenticator, recoveryCodes when made and continue when set, authenticator-updated with authenticator, and authenticator-removed. A browser that doesn't ask for JSON goes back with the status, and the rest flashed encrypted for http::result(&session, Some("enrollment")).

Events

These are in laravel_keyring::events, as in the PHP package: AuthenticatorAdded, AuthenticatorRemoved, RecoveryCodesGenerated, RecoveryCodeUsed, EnrollmentRefused (invalid, not_allowed, frozen or password), AuthenticatorRemovalRefused (last_factor or frozen) and AccessRefused. They carry the authenticator as plain values (its ID, factor and name) rather than a model. See Events.