Factors
On this page
- Introduction
- Registering Factors
- Built-in Factors
- Password
- Authenticator Apps (TOTP)
- Email Codes
- Recovery Codes
- Passkeys and Security Keys
- Single Sign-On
- Categories
- Writing a Code Factor
- Collecting Details at Enrollment
- Writing Any Other Factor
- Optional Contracts
- Showing a Factor in the Frontend
- Using Your Own Authenticator Model
- Factor Reference
- Built-in Factors Table
- Factor Methods
Introduction
A factor is one way a user proves who they are, such as a password, an authenticator app or a passkey. Each user's copy of a factor is an authenticator, a row in keyring_authenticators, the PHP package's table. A factor's key, such as totp or passkey, appears in URLs like /login/challenge/totp. Keys are lowercase letters, digits and dashes.
The factors are the PHP package's, with the same keys, categories, priorities and stored rows, so an authenticator added on either side works on the other. The exception is Ed25519 passkeys, which the crate can't verify (see Signature Algorithms).
Registering Factors
Keyring's own factors are settings in KeyringConfig, not a list of classes:
use laravel_keyring::KeyringConfig;use laravel_keyring::config::{EmailCodes, KeyFactor, KeyProfile, Totp}; laravel::Application::configure().with_config(|config, _| { let keyring = config.section_mut::<KeyringConfig>(); keyring.factors.totp = Some(Totp { window: 0, issuer: Some("Acme Staff".into()), ..Totp::default() }); keyring.factors.recovery_codes = None; keyring.webauthn.security_keys = Some(KeyProfile::security_keys()); keyring.webauthn.keys = vec![KeyFactor::new("backup-key", KeyProfile::security_keys())]; keyring.email_codes = Some(EmailCodes::as_extra_step());});| Setting | Factor | Default |
|---|---|---|
factors.password |
password |
On |
factors.totp |
totp, with window, issuer and algorithm |
On |
factors.recovery_codes |
recovery, with count |
On, eight codes |
factors.passkeys |
passkey |
On |
webauthn.security_keys |
security-key |
Off |
webauthn.keys |
More WebAuthn second factors under keys of their own | None |
email_codes |
email-code |
Off |
With nothing set, the crate has the password, authenticator apps, recovery codes and passkeys. The PHP package's Keyring::factors() with nothing listed has the password alone, so set the others to None or false to match. Single sign-on is a feature rather than a factor setting: see Single Sign-On.
Factors of your own go on the provider, as Keyring::extend() adds them:
| Method | For |
|---|---|
code_factor(CodeFactor::new(key, name, sender)) |
A factor that sends a code. See Writing a Code Factor. |
second_factor(SecondFactor::new(key, name, factor)) |
Any other second factor. See Writing Any Other Factor. |
primary_factor(PrimaryFactor::new(key, name, factor)) |
A factor that starts a sign in. See Optional Contracts. |
Each key is checked as the application boots: one that's taken, or isn't lowercase letters, digits and dashes, stops it booting. A key names its factor across the whole process, so two applications in one process can't use one key for different factors.
Registering a factor only makes it available. Turn on features.manage_authenticators to let users add their own. NIST SP 800-63B-4 asks for at least one phishing-resistant option wherever AAL2 is offered (Sec. 2.2.2). Passkeys are one.
Warning
Don't turn a factor off while users still have its authenticators. A factor that's off behaves as one the PHP package doesn't register: its routes answer 404, it isn't offered or enrollable, and a user with one of its authenticators is refused rather than let past it, since skipping them would let the password alone through.
Built-in Factors
The table lists each factor's key, setting, categories and priority.
Password
The password stays in your users table, read through your user provider. Users change it through the password change and reset flows, not the authenticator routes. Keyring normalises a typed password to Unicode NFC before checking it, and still runs a password hash for an unknown address, so the response takes the same time.
Laravel's rehash of a password on sign in isn't ported: laravel-rust's guard keeps a fingerprint of the password hash in every session, so a new hash would sign out every other session of the user. See Differences From PHP.
Authenticator Apps (TOTP)
Keyring uses time-based one-time passwords (RFC 6238), as the PHP package does. Enrolling returns a base32 secret, an otpauth:// URL and an SVG QR code. Each authenticator records the last time step it accepted, under a row lock, so a code can't be used twice.
By default a code is valid for its own 30-second step and one step either side (window of 1), so it works for about 90 seconds. OWASP ASVS 5.0.0 requirement 6.5.5 caps a code's life at 30 seconds, so the default doesn't meet it. To meet 6.5.5 exactly, use a window of zero:
use laravel_keyring::config::Totp; keyring.factors.totp = Some(Totp { window: 0, ..Totp::default() });The widest window is 1. A wider one stops the application booting.
Keyring uses HMAC-SHA1 by default, as RFC 6238 does. If you control which apps users install, use SHA-256 or SHA-512:
use laravel_keyring::config::{Totp, TotpAlgorithm}; keyring.factors.totp = Some(Totp { algorithm: TotpAlgorithm::Sha256, ..Totp::default() });The QR code and URL then say algorithm=SHA256, and enrolling returns the algorithm. Existing authenticators keep their digest, so the setting only affects apps added afterwards. Signing in checks each authenticator with the digest it was set up with, as its meta.algorithm says.
The issuer is app.name unless issuer says otherwise. The account name is the user's mail address, or their ID when they have none, since laravel-rust's user doesn't say its username. The QR code is the qrcode crate's SVG, 192 pixels across with no margin.
Email Codes
This factor emails an eight-digit code to the user's current address. It's opt in, as in the PHP package: NIST SP 800-63B-4 doesn't accept email as an authenticator at any level (Sec. 3.1.3.1), and whoever controls the inbox can reset the password. There's no plain email code factor to turn on, only the extra step:
use std::time::Duration;use laravel_keyring::config::EmailCodes; keyring.email_codes = Some(EmailCodes { length: 6, expire_after: Duration::from_secs(5 * 60), max_guesses: 3, ..EmailCodes::as_extra_step()});The defaults are eight digits, ten minutes and five wrong guesses. Under six digits, or over ten minutes (OWASP ASVS 5.0.0, requirements 6.5.4 and 6.5.5), stops the application booting.
Each code is sent only when the client asks (see Sending Codes). Codes share one guess limit within a sign in, a new code replaces the old one, a code works once, and it's stored as a keyed hash. Codes and guess counts live in the default cache store, under the PHP package's keys and JSON, not the session, so these rules hold on any session driver. With the memory store, each server keeps codes of its own.
Enrolling sends a code to the current address. A user has at most one, and enrolling again replaces it. Five wrong codes stop the enrollment for 15 minutes from the first, counted by user. The code goes out at once, in Keyring's own email with the PHP package's wording, to the user's mail_address(). notifications.verification_code() or email_codes.mail_using replaces it (see Emails a Flow Needs). A user with no address is sent nothing.
What Turning Email Codes On Means
An emailed code is a step at sign in, not a second factor, exactly as in the PHP package. Its category is Category::Address, which counts toward no assurance level. So for an account whose only methods are a password and an email code:
- A policy with
if_enrolled(), such as the default, asks for both.Requirement::aal2()without it turns the account away, so useRequirement::steps(2)instead. - The session is AAL1, which doesn't satisfy
RequireAssurance::aal2(). Those routes send the user to yourenrollment_url. - The account has no second factor. Its password needs the longer minimum length, and an email change is confirmed from the current address.
- It gets no recovery codes.
If routes need AAL2, or your app tells users they have two-factor authentication, offer an authenticator app or passkeys alongside email codes.
Recovery Codes
A set is eight single-use codes, shown once, in the PHP package's form, stored as keyed hashes (HMAC-SHA256 with a key derived from APP_KEY). Typing is case-insensitive, and spaces and dashes are ignored. Fortify's sets, imported with keyring:import, are 20 letters and digits, and their case matters.
A user has at most one set, and generating a new one replaces it. Users get a set with their first extra factor. Codes are a fallback, so they're never the default (see Recovery Codes). factors.recovery_codes' count changes the size of a set, and a count of 0 stops the application booting. RecoveryCodes::generate(&encrypter) makes a set in your own code, and RecoveryCodes::generate_count() one of another size.
When you rotate APP_KEY, put the old key in APP_PREVIOUS_KEYS so existing codes keep working.
Passkeys and Security Keys
Both use one WebAuthn driver with two profiles, as in the PHP package. Passkeys (factors.passkeys) are discoverable and always verify the user when they sign in alone. Security keys (webauthn.security_keys) are a second factor, and require_attestation limits them to keys whose maker vouches for them. webauthn.keys adds more security key factors under keys of their own, as WebAuthn::securityKeys()->as(), but a second passkey factor that signs in alone isn't there. See Passkeys & Security Keys.
Single Sign-On
The sso factor signs users in with the providers in sso.providers, with features.sso on: Google, Microsoft, GitHub or any OpenID Connect provider. It works as the PHP package's SingleSignOn does: each linked account is an authenticator, matched on issuer and subject, never on email, and stored under the PHP package's credential_id, so a link either side made signs in on the other. It counts as knowledge, is never the default, never offered on the challenge page, and never comes with recovery codes. See Single Sign-On.
Categories
Every verification proves one or more categories, laravel_keyring::Category:
Knowledge: something the user knows, such as a password.Possession: something they have, such as a phone, a key or recovery codes.Inherence: something they are, such as a fingerprint their authenticator checked.Address: something sent to an address they own, such as an emailed code. It isn't an authentication factor and never raises the level.
Policies count distinct categories, so a password and a PIN are still one factor. AAL2 and AAL3 need Possession among what was proved (NIST SP 800-63B-4, Sec. 2.2.1). See Policies.
A factor of your own says what it proves once, for the factor, with categories([...]). A PHP factor's categories() is given the authenticator and can vary with it.
Writing a Code Factor
If your factor sends a one-time code, give the provider a CodeFactor with a sender that implements SendsCodes, as a PHP CodeFactor subclass's deliver(). Keyring handles sending, checking, expiry, single use, guess limits, resends and enrollment, as for email codes, under the factor's own key:
use laravel_keyring::KeyringServiceProvider;use laravel_keyring::codes::{CodeFactor, Input, NewAuthenticator, Recipient, SendsCodes}; struct TextMessage; impl SendsCodes<User> for TextMessage { async fn deliver(&self, _user: &User, to: &Recipient, code: &str) -> laravel::Result<()> { let number = to.secret.as_deref().unwrap_or_default(); laravel::sms::to(number).send(format!("Your sign-in code is {code}")).await?; Ok(()) } async fn new_authenticator(&self, _user: &User, input: &Input) -> laravel::Result<NewAuthenticator> { // Validate the number, then keep it in the (encrypted) secret. let phone = input.get("phone").and_then(|phone| phone.as_str()).unwrap_or_default(); Ok(NewAuthenticator { secret: Some(phone.to_owned()), ..NewAuthenticator::default() }) }} laravel::Application::configure().with_providers(|providers| { providers.add( KeyringServiceProvider::<Users>::new() .code_factor(CodeFactor::new("sms", "Text message", TextMessage).length(6)), );});length (default 8, at least 6), expire_after (default ten minutes, at most ten) and max_guesses (default 5) set the factor's own. A code of more than 18 digits, or a factor allowing no wrong guesses, also stops the application booting, beyond the PHP package's bounds.
A code factor counts as possession, so a password and a code are AAL2 and the first one comes with recovery codes. categories([...]) says what it proves instead, as a subclass's own categories(), and limits(FactorLimits { .. }) gives its answers limits of their own, as a subclass's own limits():
use laravel_keyring::codes::{Category, CodeFactor, FactorLimits, Limit}; CodeFactor::new("sms", "Text message", TextMessage) .categories([Category::Possession]) // Three answers a minute for an account, at most 20 wrong in a row, and the // config's limit on an address. .limits(FactorLimits { per_account: Limit::At(3), consecutive: Limit::At(20), ..FactorLimits::default() });Each of per_ip, per_account, consecutive and consecutive_elsewhere is a Limit::At(n), Limit::Off for none, or Limit::Inherit, the default, for the config's. per_account can't be off, which stops the application booting. one_per_user() keeps a user to one.
sent_to_an_address() makes it a step like an emailed code, counting toward no level. Unlike an emailed code, such a step goes wherever whoever added it said, so it's guarded as a factor is, as in the PHP package: adding it takes the password where a first second factor would, and one added without it isn't asked for, and freezes the account, until it's established.
Beginning an enrollment of a code factor (POST /user/authenticators/{factor}) is under the keyring limiter (limits.forms), where the PHP package doesn't limit it.
Collecting Details at Enrollment
SendsCodes::new_authenticator() collects something such as a phone number when the user adds the factor, as overriding newAuthenticator does. Whatever it returns in secret (encrypted at rest), meta and name is saved once the enrollment is confirmed. Keyring doesn't validate the request, so validate it there and fail with an InvalidInput. deliver() then reads the number from to.secret. Because codes go to that address, confirming the enrollment proves the user can receive them.
Writing Any Other Factor
Any other second factor is a SecondFactor, given something that implements ChecksProofs, and optionally Enrolls so users can add it:
use laravel::http::Request;use laravel_keyring::KeyringServiceProvider;use laravel_keyring::second::{ Authenticator, ChecksProofs, Enrollment, Enrolls, Input, NewAuthenticator, SecondFactor,};use serde_json::{Map, Value, json}; /// A hardware token, by its serial number.struct HardwareToken; impl ChecksProofs<User> for HardwareToken { async fn verify(&self, _user: &User, token: &Authenticator, _request: &Request, input: &Input) -> laravel::Result<bool> { let code = input.get("code").and_then(Value::as_str).unwrap_or_default().to_owned(); let serial = token.secret.clone().unwrap_or_default(); // Each code once: the row is locked while the server is asked, and // the code is kept as the last one used. let accepted = token_server_accepts(&serial, &code).await; token .consume(|mut stored| { let last = stored.meta.get("last_code").and_then(Value::as_str); if !accepted || last == Some(code.as_str()) { return None; } stored.meta.insert("last_code".into(), json!(code)); Some(stored) }) .await }} impl Enrolls<User> for HardwareToken { async fn begin(&self, _user: &User, _request: &Request, input: &Input) -> laravel::Result<Enrollment> { let serial = input.get("serial").and_then(Value::as_str).unwrap_or_default(); Ok(Enrollment::default().prop("serial", serial).state("serial", serial)) } async fn confirm(&self, _user: &User, state: &Map<String, Value>, _request: &Request, input: &Input) -> laravel::Result<Option<NewAuthenticator>> { let serial = state.get("serial").and_then(Value::as_str).unwrap_or_default(); let code = input.get("code").and_then(Value::as_str).unwrap_or_default(); Ok(token_server_accepts(serial, code).await.then(|| NewAuthenticator { secret: Some(serial.to_owned()), ..NewAuthenticator::default() })) }} laravel::Application::configure().with_providers(|providers| { providers.add( KeyringServiceProvider::<Users>::new().second_factor( SecondFactor::new("hardware-token", "Hardware token", HardwareToken) .enrollable(HardwareToken), ), );});token_server_accepts() is yours. verify() runs inside the timebox and after rate limiting, and answers whether the proof holds rather than returning a Verification. Use Authenticator::consume() for anything single-use: it reloads the authenticator under a row lock and saves what your closure returns, so two requests with the same proof can't both pass.
ChecksProofs::challenge() gives the challenge page props of its own. Keyring doesn't validate your factor's fields: the factor does, failing with InvalidInput.
Optional Contracts
The PHP package's contracts are separate types here:
| PHP | Rust |
|---|---|
PrimaryFactor |
primary::PrimaryFactor, given something that implements IdentifiesUsers, to the provider's primary_factor(). |
DiscoverableFactor |
IdentifiesUsers::login_options(), served at GET /login/{factor}/options. |
Enrollable |
second::Enrolls, given to a factor's enrollable(). |
SendsCodes |
codes::SendsCodes, given to a CodeFactor. |
A primary factor starts a sign in at POST /login/{factor}, and with sign_in::attempt() and SignInWith::Factor(key). Its IdentifiesUsers has validate() (the fields a sign in sent, checked before anything else, the rate limits included), identify() (the user, and the authenticator with Identified::by(), from the request), verify() (a proof on the challenge and confirm pages), login_options() and stall(). The factor's builder has categories(), phishing_resistant(), device_bound(), answers_challenges(), priority(), error_key(), identified_by([...]), enrollable() and one_per_user(). This is the contract app's partner factor, which signs in whoever a one-time token names:
use laravel::auth::UserProvider;use laravel::http::Request;use laravel_keyring::primary::{Authenticator, Category, Identified, IdentifiesUsers, Input, PrimaryFactor};use serde_json::Value; struct Partner; impl IdentifiesUsers<User> for Partner { async fn identify(&self, _request: &Request, input: &Input) -> laravel::Result<Option<Identified<User>>> { let token = input.get("token").and_then(Value::as_str).unwrap_or_default(); let Some(id) = laravel::cache::pull::<i64>(&format!("partner:{token}")).await? else { return Ok(None); }; Ok(Users.find(&id).await?.map(Identified::new)) } // Its proof is who it found, so there's nothing more to check. async fn verify(&self, _user: &User, _authenticator: &Authenticator, _request: &Request, _input: &Input) -> laravel::Result<bool> { Ok(true) }} KeyringServiceProvider::<Users>::new().primary_factor( PrimaryFactor::new("partner", "Partner", Partner) .categories([Category::Knowledge]) .identified_by(["token"]),);Each goes through what the password and passkeys go through: the account's sign-in limits (lock_after and clear_account() included), the pipeline with your steps, risk, the policy and the challenge, with the same events and log entries. A primary factor's challenge page props are [], and an Identified::by(user, id) naming a row that isn't the user's confirmed authenticator of that factor is taken as nobody found, after stall().
An Enrolls factor enrolls in two steps, through /user/authenticators/{factor} under the same rules as Keyring's own. begin() returns an Enrollment, whose prop()s go to the browser and whose state() stays in the session for 15 minutes. confirm() gets that state, without Keyring's own keyring. keys, checks the proof and returns a NewAuthenticator, or None. Keyring counts it as verified, so return one only when the proof shows it works. one_per_user() makes a new authenticator replace the old one.
Showing a Factor in the Frontend
The challenge page picks a component by factor key (see Frontend). Add a line to your factor map for each factor, as the starter kit's resources/js/keyring/factors.tsx does. A code factor can reuse the TOTP component.
Using Your Own Authenticator Model
Not available: there are no Eloquent models, so there's no useAuthenticatorModel(). Authenticators are rows in keyring_authenticators. UserKeyring::of(&user) reads a user's, and primary::Authenticator is what a factor of your own is given. See Differences From PHP.
Factor Reference
Built-in Factors Table
| Key | Setting | Categories | Starts a Sign In | Users Add It | Priority |
|---|---|---|---|---|---|
password |
factors.password |
knowledge | yes | no | 40 |
totp |
factors.totp |
possession | no | yes | 60 |
email-code |
email_codes |
address (not a factor) | no | yes, one | 30 |
recovery |
factors.recovery_codes |
possession | no | yes, one set | 0 |
passkey |
factors.passkeys |
possession, plus inherence when the user was verified | yes | yes | 100 |
security-key |
webauthn.security_keys |
possession, plus inherence when the user was verified | no | yes | 90 |
sso |
features.sso |
knowledge | yes, from the provider's callback | yes, one per linked account | 30 |
When Keyring needs another factor, it offers the user's default authenticator first, then the rest by priority.
Factor Methods
A factor of your own is a builder plus a trait, rather than a class with methods to override:
| PHP Method | Rust |
|---|---|
key |
The first argument to PrimaryFactor::new(), SecondFactor::new() or CodeFactor::new(). |
categories($authenticator) |
categories([...]), once for the factor. |
verify($attempt, $authenticator, $request) |
IdentifiesUsers::verify() or ChecksProofs::verify(), answering bool. |
phishingResistant($authenticator), deviceBound($authenticator) |
phishing_resistant() and device_bound(), once for the factor. |
attested($authenticator) |
Not available. |
priority |
priority(n). |
authenticators($user, $stored) |
Not available: there are no virtual authenticators. |
challenge($attempt, $authenticator) |
ChecksProofs::challenge(). A primary factor gives none. |
rules |
Your own validation inside verify() or validate(). |
limits($request, $attempt) |
CodeFactor::limits() for a code factor. Others count under the configured limits. |
errorKey |
error_key(field). |
present($authenticator) |
Not available: every authenticator is presented as Keyring's are. |
consume($authenticator, $callback) |
Authenticator::consume(). |