Signing InFactors

Factors

On this page

Introduction

A factor is one way a user proves who they are, such as a password, an authenticator app or a passkey. Each factor implements Keyring\Contracts\Factor, so adding one needs no new routes or tables.

Each user's copy of a factor is an authenticator, stored as a Keyring\Models\Authenticator row in keyring_authenticators. A factor's key, such as totp or passkey, appears in URLs like /login/challenge/totp. Keys are lowercase letters, digits and dashes. challenge isn't allowed, since /login/challenge is a route of its own.

Registering Factors

List the factors your app offers in Keyring::factors, in the boot() method of your KeyringServiceProvider:

PHP
use Keyring\Facades\Keyring;use Keyring\Factors\Password;use Keyring\Factors\RecoveryCodes;use Keyring\Factors\Totp;use Keyring\Factors\WebAuthn; Keyring::factors([    Password::class,    WebAuthn::passkeys(),    WebAuthn::securityKeys(),    Totp::class,    RecoveryCodes::class,]);

Without this call, Keyring uses the password alone. keyring:install writes the list for the sign-in methods you pick. The list takes class names, instances and closures that receive the container:

PHP
Keyring::factors([    Password::class,    fn ($app) => $app->make(Totp::class, ['window' => 0, 'issuer' => 'Acme Staff']),    new RecoveryCodes(count: 10),]);

To add a factor from a package without replacing the list, use Keyring::extend. Keyring registers the factor under the key you pass, and the factor's key() must return the same value, or Keyring throws an InvalidArgumentException:

PHP
Keyring::extend('sms', fn ($app) => $app->make(SmsCode::class));

Registering a factor only makes it available. Turn on Features::manageAuthenticators() 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 remove a factor while users still have its authenticators. Keyring refuses those users with keyring::keyring.unavailable and reports a Keyring\Exceptions\UnregisteredFactor, since skipping them would let the password alone through. Register the factor again, or delete or migrate its rows. Until then, $authenticator->factor() throws Keyring\Exceptions\UnknownFactor, which is a 404 when the key is in a URL.

Built-in Factors

The table lists each factor's key, class, categories and priority.

Password

The password stays in your users table, so resets and Laravel's helpers keep working. 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 (see Password Rules), and it still runs a password hash for an unknown address, so the response takes the same time.

Authenticator Apps (TOTP)

Keyring uses time-based one-time passwords (RFC 6238). Enrolling returns a 32-character 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. Keyring keeps it, because with no window, codes typed near the end of a step would be refused. To meet 6.5.5 exactly, use a window of zero:

PHP
Keyring::factors([Password::class, fn ($app) => $app->make(Totp::class, ['window' => 0])]);

The widest window is Totp::MAX_WINDOW (1). Any other value throws a LogicException when the factor is built.

RFC 6238 defaults to SHA-1, and Keyring uses HMAC-SHA1 by default. Some popular apps ignore any other digest, and OWASP ASVS allows HMAC-SHA-1 as a legacy algorithm. If you control which apps users install, use SHA-256 or SHA-512:

PHP
Keyring::factors([Password::class, fn ($app) => $app->make(Totp::class, ['algorithm' => 'sha256'])]);

The only accepted values are sha1, sha256 and sha512, and anything else throws an InvalidArgumentException. 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.

Email Codes

This factor emails an eight-digit code to the user's current address. It's opt-in. 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. Registering the plain class throws an InvalidArgumentException. To accept the risk, use asExtraStep():

PHP
Keyring::factors([Password::class, Totp::class, EmailCode::asExtraStep()]);

The defaults are eight digits, ten minutes and five wrong guesses. Change them with named arguments:

PHP
EmailCode::asExtraStep(length: 6, expireAfter: '5m', maxGuesses: 3);

The length can't be under six digits, and the expiry can't be over ten minutes (OWASP ASVS 5.0.0, requirements 6.5.4 and 6.5.5). Anything outside those bounds throws a LogicException.

Each code is sent only when the user 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 cache store your rate limits use (cache.limiter), not the session, so these rules hold on any session driver, including cookie. With the array store, a code is forgotten before it's typed.

Enrolling sends a code to the current address. A user has at most one, and enrolling again replaces it. Once the guess limit is reached during enrollment, no code is sent until 15 minutes (enrollments.keep_for) after the first wrong guess. Guesses are counted per user, not per browser. The code is sent in Keyring's verification_code notification, which Keyring::notifications() can replace.

Some mail apps offer to copy a code from an email, or to fill it in on the page that asked for it. There's no standard or markup for this, and none of them publish what they look for, so it's their guess. Keyring's email gives them what they seem to need: Your verification code is 48291374, the code as one run of digits beside the word "code", and a plain-text part saying the same. No code is ever in an image. It isn't in the subject either: some apps look there too, but mail providers and apps keep subjects in their logs, which outlive the code. If you replace the notification, put the code in its body the same way, and give the code field on your challenge page autocomplete="one-time-code" and inputmode="numeric", as the factor component does.

Signing In From the Email

To put a button beside the code, so users can finish signing in from the email, add withLink(). It's off unless you do:

PHP
Keyring::factors([Password::class, Totp::class, EmailCode::asExtraStep()->withLink()]);

The sign-in email then carries the code and a "Sign in" button. The button proves what the code proves, that the user can read the mailbox, so it's still Category::Address and never a factor, and what turning email codes on means still holds. Step-up and enrollment emails carry the code alone.

The link carries the code, encrypted with APP_KEY together with the sign in it was sent for. Nothing else is stored. It works while its code does: once, for the code's lifetime and no longer than the sign in's, and using either the link or the code uses up both. A newer code, running out of guesses or the end of the sign in ends it too.

Opening the link changes nothing. It opens the sign-in-link page, which does one of two things:

  • In the browser that started the sign in, whose session holds it, the page has a button that posts the code. That finishes the sign in exactly as typing the code would, through the same pipeline, rate limits, guess limit, events and security log entries.
  • Anywhere else, such as the mail app's own browser, a phone, or a mail scanner, the page asks for the code from the email to be typed where the sign in started. It finishes nothing, and it doesn't show the code: scanners keep the pages they open, and some publish them, while whoever opened the link has the email the code is in.

So a mail scanner that opens every link signs nobody in and uses nothing up, and a link opened on another device never signs that device in. Nobody can approve a sign in from their inbox either: if someone with the password starts one, the owner would have to type the code into that person's browser. Say so on the page, as below.

The link is built on APP_URL, or on Keyring::linkRootUsing() when you set it, like Keyring's other emailed links. The browser sends the session cookie only to the host it belongs to, so someone who signed in on another host, such as www.example.com with APP_URL set to https://example.com, or a tenant's subdomain, opens the link without the session that holds the sign in, and the page says it's the wrong browser. Make the link's root the host people sign in on, or share the session cookie across those hosts with SESSION_DOMAIN.

The page receives these props:

Prop
code The code the button posts, while sameBrowser is true. Otherwise null.
sameBrowser Whether this browser holds the sign in the link was sent for.
url Where the button posts code, while sameBrowser is true. Otherwise null.
expiresAt When the link stops working, as an ISO 8601 date, or null once it can't sign in. It's null in a browser that has started signing in again since, too: the link's code can't finish the newer attempt.

What the page shows follows from them:

  • sameBrowser: a "Sign in" button that posts { code } to url. The answer is the one verifying gives: the next page, the challenge for another factor, or an error on code.
  • An expiresAt without sameBrowser: "This button only works in the browser where you started signing in. Type the code from the email in that browser instead. If you didn't start signing in, don't type it anywhere, and change your password."
  • No expiresAt: "This link has expired or has been used. Go back to where you started signing in, and send a new code from there."

The page's route is GET /login/challenge/email-code/link (keyring.login.link), and its button posts to POST /login/challenge/email-code/link (keyring.login.link.store). Both answer 404 until withLink() is on. See The Pages Emailed Links Open, and for a frontend Laravel doesn't serve, Emailed Links.

What Turning Email Codes On Means

An emailed code is a step at sign in, not a second factor. 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 ifEnrolled(), such as the default, asks for both. Requirement::aal2() without it turns the account away, so use Requirement::steps(2) instead.
  • The session is AAL1, which doesn't satisfy keyring:aal2. Those routes send the user to your enrollment_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 keyring: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 form xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xx. Each carries 128 random bits as 26 base32 characters, and Keyring stores it as a keyed hash. Typing is case-insensitive, and spaces and dashes are ignored.

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). Once every code is used, the set stops counting as a factor. Fortify's sets, imported with keyring:import, are 20 letters and digits. Their case matters, so an imported code must be typed exactly as shown.

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. Passkeys are discoverable and always verify the user, so they can sign in without a username. Security keys are a second factor, and requireAttestation() limits them to keys whose maker vouches for them. See Passkeys & Security Keys.

Single Sign-On

SingleSignOn signs users in with the providers in sso.providers: Google, Microsoft, GitHub or any OpenID Connect provider. Each linked provider account is an authenticator, matched on the provider's issuer and subject, never on email. It counts as knowledge, because it stands in for the password. It's never the default, never offered on the challenge page, and never comes with recovery codes. A link can also confirm a step-up by sending the user back to the provider, as its freshness says. See Single Sign-On.

Categories

Every verification proves one or more categories from Keyring\Enums\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. Category::authenticates() tells the two kinds apart. One that goes to an address of its own rather than the account's is still guarded as a factor is when it's added (see Writing a Code Factor).

Policies count distinct categories, so a password and a PIN are still one factor. See Policies.

AAL2 and AAL3 need Possession among what was proved (NIST SP 800-63B-4, Sec. 2.2.1), and a biometric counts only with the authenticator it unlocks. If your factor checks something the user is, report Inherence only when a device they hold made the check, and report Possession too. A factor that reports Inherence alone leaves the session at AAL1.

A factor declares the categories it expects in categories, which Keyring uses to plan what to offer. The categories that count are the ones in the Verification that verify returns.

Writing a Code Factor

If your factor sends a one-time code, extend Keyring\Factors\CodeFactor. It handles sending, checking, expiry, single use, guess limits, resends and enrollment. A code only verifies the authenticator it was sent to, so a user with two phones can't send a code to one and type it against the other. Give it a key, a default name and a delivery method:

PHP
namespace App\Keyring; use App\Notifications\SmsCode as SmsCodeNotification;use Illuminate\Contracts\Auth\Authenticatable;use Illuminate\Database\Eloquent\Model;use Keyring\Factors\CodeFactor;use Keyring\Models\Authenticator; class SmsCode extends CodeFactor{    protected int $length = 6;     protected int $ttl = 300;     public function key(): string    {        return 'sms';    }     protected function defaultName(Authenticatable&Model $user): string    {        return 'Text message';    }     protected function deliver(Authenticatable&Model $user, Authenticator $authenticator, string $code): void    {        $user->notify(new SmsCodeNotification($authenticator->secret, $code));    }}

Add it to your factors:

PHP
Keyring::factors([Password::class, Totp::class, SmsCode::class]);

deliver() sends every code: at sign in, at step-up, and to confirm enrollment, when $authenticator->exists is false. To send something that needs the sign in or step-up itself, such as a link to it, also override deliverFor(Attempt $attempt, Authenticator $authenticator, string $code), which sends those two and calls deliver() unless you change it. $attempt->purpose says which it is, and $attempt->user() who it's for. EmailCode::withLink() works this way.

Override $length (default 8, at least 6), $ttl (default 600, at most 600) and $maxGuesses (default 5, wrong guesses per sign-in or enrollment). Keyring checks the first two when it resolves the factors, and a LogicException names the factor if they're outside those bounds (CodeFactor::MIN_LENGTH and CodeFactor::MAX_TTL).

Code factors count as possession, with priority 30. Possession suits a code sent to a device the user holds, such as a text message (NIST restricts that kind of code without banning it; see the SMS recipe). A code sent to an address that a password alone can read should return [Category::Address] from categories, as EmailCode does.

Unlike EmailCode, which always goes to the account's own address, any other address step goes wherever whoever added it said, such as a number typed at enrollment. Someone holding a copy of a session could add one sent to themselves, and every sign-in after would need a code sent there, which a password reset wouldn't undo. So Keyring guards it as it guards a factor, though it still counts toward no level: adding one to an account with an established password and no established second factor takes the password in that request, as adding a first second factor does (see Second Factors and Step-Up), and one added without it isn't asked for at sign-in until the account has had it for authenticator_changes.established_after. Like a new factor, a new one also starts the freeze, and an established one can't be removed, renamed or replaced while the account is frozen. Keyring can't tell where a factor sends its codes, so this applies to every address step but EmailCode itself. A subclass of EmailCode counts as one with an address of its own too, since it may send its codes somewhere else.

Collecting Details at Enrollment

To collect something such as a phone number when the user adds the factor, override newAuthenticator. Whatever you put in secret (encrypted at rest) or meta is saved once the enrollment is confirmed. Keyring doesn't validate the request, so validate it here:

PHP
use Illuminate\Http\Request; protected function newAuthenticator(Authenticatable&Model $user, Request $request): Authenticator{    $phone = $request->validate(['phone' => ['required', 'string', 'max:32']])['phone'];     return $this->makeAuthenticator([        'name' => $this->nameFrom($request, $this->defaultName($user)),        'secret' => $phone,    ])->setRelation('authenticatable', $user);}

deliver then reads the number from $authenticator->secret. Because codes go to that address, confirming the enrollment proves the user can receive them.

Writing Any Other Factor

Any other factor implements Keyring\Contracts\Factor. Extending Keyring\Factors\Factor gives defaults for everything except key, categories and verify:

PHP
namespace App\Keyring; use Illuminate\Http\Request;use Keyring\Enums\Category;use Keyring\Factors\Factor;use Keyring\Login\Attempt;use Keyring\Login\Verification;use Keyring\Models\Authenticator; class HardwareToken extends Factor{    public function key(): string    {        return 'hardware-token';    }     public function categories(Authenticator $authenticator): array    {        return [Category::Possession];    }     public function verify(Attempt $attempt, Authenticator $authenticator, Request $request): ?Verification    {        $valid = $this->consume($authenticator, function (Authenticator $locked) use ($request) {            // Check the posted code against $locked, and record that it was            // used (for example in $locked->withMeta(...)).            return app(TokenServer::class)->check($locked->secret, (string) $request->post('code'));        });         return $valid ? $this->verified($authenticator) : null;    }}

verify runs inside the timebox and after rate limiting. Use consume() for anything single-use: it reloads the authenticator under a row lock and saves it when your callback returns true, so two requests with the same proof can't both pass.

Optional Contracts

Implement these when they apply:

Contract Means
PrimaryFactor Can start a sign-in by identifying the user (POST /login/{key}). It has startsLogin(), answersChallenges(), identify($request), stall() and identificationRules().
DiscoverableFactor A primary factor that needs no username, such as a passkey. Serves loginOptions($request) at GET /login/{key}/options.
Enrollable Users can add it themselves. Its methods are beginEnrollment, confirmEnrollment, multiple and enrollmentRules.
SendsCodes Sends a code when asked, through send($attempt, $authenticator).

For a PrimaryFactor, answersChallenges() returns false when the proof is who identify() found, as single sign-on does. Keyring then keeps the factor off the challenge and confirm pages. identify() must take the same time whether or not a user is found. stall() spends the time verify() would take when Keyring turns away a user without checking their proof, such as one allowSignInWhen() keeps out. Only write it when checking a proof is slow.

An Enrollable factor enrolls in two steps. beginEnrollment($user, $request) returns an Enrollment built with Enrollment::make(), whose props go to the browser and whose state stays in the session for 15 minutes. confirmEnrollment($user, $enrollment, $request) checks the proof and returns an unsaved authenticator, or null. Keyring counts that authenticator as verified, so return one only when the proof shows it works. Return false from multiple when a new authenticator replaces the old one. Replacing an established one is refused while sign-in methods are frozen.

PHP
use Keyring\Enrollment\Enrollment; public function beginEnrollment(Authenticatable&Model $user, Request $request): Enrollment{    $serial = Str::random(12);     return Enrollment::make($this->key(), props: ['serial' => $serial], state: ['serial' => $serial]);}

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. A code factor can reuse the TOTP component:

TypeScript
'sms': defineAsyncComponent(() => import('./factors/Code.vue')),

Using Your Own Authenticator Model

Extend Keyring\Models\Authenticator to add relationships or methods, then tell Keyring about your model:

PHP
use App\Models\Authenticator; Keyring::useAuthenticatorModel(Authenticator::class);

Factor Reference

Built-in Factors Table

Key Class Categories Starts a Sign In Users Add It Priority
password Password knowledge yes no 40
totp Totp possession no yes 60
email-code EmailCode::asExtraStep(), with ->withLink() for a sign-in link address (not a factor) no yes, one 30
recovery RecoveryCodes possession no yes, one set 0
passkey WebAuthn::passkeys() possession, plus inherence when the user was verified yes yes 100
security-key WebAuthn::securityKeys() possession, plus inherence when the user was verified no yes 90
sso SingleSignOn 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

Defaults come from Keyring\Factors\Factor:

Method Default Purpose
key none The factor's key.
categories($authenticator) none What it's expected to prove.
verify($attempt, $authenticator, $request) none Checks the proof. Returns a Verification, or null when it's wrong.
phishingResistant($authenticator) false Whether the proof is bound to your origin. Only WebAuthn returns true. An established authenticator that returns true can also make a change while sign-in methods are frozen, so its verify() must check the answer against that challenge.
deviceBound($authenticator) false Whether the secret can't leave its device.
attested($authenticator) false Whether a verified attestation vouches for it. AAL3 accepts a device-bound key only when this is true.
priority 50 Higher numbers are offered first.
authenticators($user, $stored) stored rows with this key The user's authenticators. Return virtual ones for state kept elsewhere.
challenge($attempt, $authenticator) [] Extra props for the challenge page. Called on every load, so it must be safe to repeat.
rules code required, up to 64 characters Validation for a verification request, checked against the body.
limits($request, $attempt) per account and per IP Rate limits. See Rate Limiting.
errorKey code The form field failures are reported on.
present($authenticator) factor, id, name, createdAt, lastUsedAt How the authenticator appears on settings pages. The challenge page omits the two dates.

These helpers are also on Factor: verified($authenticator, $categories, $phishingResistant, $deviceBound) builds the Verification, consume($authenticator, $callback) runs a single-use check under a row lock, makeAuthenticator($attributes) makes an unsaved authenticator, nameFrom($request, $default) reads the optional name (trimmed, up to 64 characters), and normalizeCode($code) strips spaces and dashes.