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 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. Keyring for Go doesn't have every factor yet: security keys, and second factors of your own other than code factors, aren't there. A user with one of those, added on the PHP side, is refused at sign in rather than let past it. See Differences From PHP.

Registering Factors

Keyring's own factors are settings in keyring.Config, not a list of classes:

Go
k := keyring.New[models.User](func(cfg *keyring.Config) {    cfg.Factors.TotpWindow = 0    cfg.Factors.TotpIssuer = "Acme Staff"    cfg.Factors.Passkeys = true    cfg.Factors.EmailCodes = keyring.EmailCodesAsExtraStep()})
Setting Factor Default
None password Always on
Factors.TotpWindow, TotpIssuer, TotpAlgorithm totp Always on
Factors.RecoveryCodes recovery, the size of a set Always on, eight codes
Factors.Passkeys passkey On
Factors.EmailCodes email-code Off (nil)
Factors.SingleSignOn sso Off

Set the fields one at a time: assigning the whole Factors struct leaves RecoveryCodes at zero, which Register refuses.

With nothing set, Keyring for Go has the password, authenticator apps, recovery codes and passkeys. The PHP package's Keyring::factors() with nothing listed has the password alone, and there's no turning authenticator apps or recovery codes off here. See Single Sign-On for its providers.

A code factor of your own goes to AddCodeFactor, as Keyring::extend() adds one:

Method For
AddCodeFactor(keyring.CodeFactor[U]{...}) A factor that sends a code. See Writing a Code Factor.

Each key is checked by Register: one that's taken, or isn't lowercase letters, digits and dashes, stops it.

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 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 with the unavailable 422 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 from your user type's Password field. 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 Go's hash writes and checks bcrypt ($2y$, $2a$ and $2b$), both ways with PHP. It has no Argon2, so a password a PHP app hashed with Argon2 can't be checked here. Laravel's rehash of a password on sign in isn't ported: Laravel Go'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, through its own totp package. 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 (Factors.TotpWindow 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:

Go
cfg.Factors.TotpWindow = 0

The widest window is 1. A wider one stops Register.

Keyring uses HMAC-SHA1 by default, as RFC 6238 does. If you control which apps users install, use SHA-256 or SHA-512:

Go
import "keyringauth.com/go/totp" cfg.Factors.TotpAlgorithm = totp.SHA256

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 Factors.TotpIssuer says otherwise. The account name is the user's Config.Username field. The QR code is drawn with rsc.io/qr, as an SVG 192 pixels across with no margin.

Secrets are read more loosely than Google2FA reads them (any case, spaces and padding, at least 10 bytes), so a hand-imported secret of 20 or 52 characters works here and is an error on the PHP side.

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:

Go
codes := keyring.EmailCodesAsExtraStep()codes.Length = 6codes.ExpireAfter = 5 * time.Minutecodes.MaxGuesses = 3cfg.Factors.EmailCodes = codes

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 Register.

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.

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 Config.EnrollmentsFor (15 minutes) from the first, counted by user. The code goes out at once, with the mailer, in Keyring's own email (keyring.VerificationCode) with the PHP package's wording. EmailCodes.Mail replaces it (see Emails a Flow Needs). Register refuses emailed codes with verification_code in Notifications.Off.

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, as the PHP package's does: 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 email, 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, use WithLink(), as the PHP package's EmailCode::asExtraStep()->withLink(). It's off unless you do:

Go
cfg.Factors.EmailCodes = keyring.EmailCodesAsExtraStep().WithLink()

WithLink() sets EmailCodes.Link, which you can also set yourself. 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 keyring.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, as the PHP package seals it, so either side can open the other's link and read it with the same APP_KEY. But a link only signs in on the side that sent it: the code and the sign in's attempt live there, and the code is checked there, as codes are. On the other side it ends, as a link for a sign in it never saw would. 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 Config.LinkRoot 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 the PHP package's 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 are only there while EmailCodes.Link is on, a 404 otherwise. The page is counted by Limits.Pages, as the other pages emailed links open, and the button by the challenge's own limits. A token Keyring didn't make is logged as link_refused, with link sign_in_link (see The Security Log). See The Pages Emailed Links Open, and for a frontend Keyring doesn't serve, Emailed Links. The starter kit doesn't turn the link on, and has no sign-in-link page.

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 keyring.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. keyring.AAL2.Requirement() without it turns the account away, so use keyring.RequireSteps(2) instead.
  • The session is AAL1, which doesn't satisfy RequireAssurance. Those routes send the user to your Config.EnrollmentURL.
  • 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). Once every code is used, the set stops counting as a factor. Factors.RecoveryCodes changes the size of a set, and fewer than one stops Register. k.GenerateRecoveryCodes(ctx) makes a set in your own code: the Codes to show once, and the Secret to store, already encrypted.

When you rotate APP_KEY, put the old key in APP_PREVIOUS_KEYS so existing codes keep working. A set is encrypted again under the current key when one of its codes is used.

Passkeys and Security Keys

Passkeys (Factors.Passkeys) are discoverable and always verify the user when they sign in alone. Security keys, WebAuthn::securityKeys() and its as(), aren't there yet, and neither is attestation other than none. See Passkeys & Security Keys.

Single Sign-On

The sso factor signs users in with the providers in Config.SSO, with Factors.SingleSignOn 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, the PHP package's Category, which are string constants here:

  • keyring.Knowledge: something the user knows, such as a password.
  • keyring.Possession: something they have, such as a phone, a key or recovery codes.
  • keyring.Inherence: something they are, such as a fingerprint their authenticator checked.
  • keyring.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 code factor of your own proves possession, or the address with SentToAnAddress. It can't say it proves anything else.

Writing a Code Factor

If your factor sends a one-time code, give AddCodeFactor a keyring.CodeFactor[U] whose Sender implements keyring.SendsCodes[U], 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:

Go
package factors import (    "context"     "go.laravel.com/validation"    "go.laravel.com/web"     keyring "keyringauth.com/go"     "app/models") // Gateway is your text message provider.type Gateway interface {    Send(ctx context.Context, number, message string) error} // TextMessages sends sign-in codes by text message.type TextMessages struct {    Gateway Gateway} // Deliver texts the code to the number the sign-in method keeps.func (t TextMessages) Deliver(ctx context.Context, _ *models.User, to keyring.CodeRecipient, code string) error {    if to.Secret == nil {        return nil    }     return t.Gateway.Send(ctx, *to.Secret, "Your sign-in code is "+code)} // NewAuthenticator keeps the number given as phone in the (encrypted) secret.func (TextMessages) NewAuthenticator(_ context.Context, _ *models.User, input map[string]any) (keyring.NewCodeAuthenticator, error) {    number, _ := input["phone"].(string)    if number == "" {        return keyring.NewCodeAuthenticator{}, &web.InputError{Fields: validation.Errors{            {Field: "phone", Messages: []string{"The phone field is required."}},        }}    }     return keyring.NewCodeAuthenticator{Secret: &number}, nil}
Go
k.AddCodeFactor(keyring.CodeFactor[models.User]{    Key:         "sms",    DefaultName: "Text message",    Sender:      factors.TextMessages{Gateway: gateway},    Length:      6,})

Length (zero is 8, at least 6), ExpireAfter (zero is ten minutes, at most ten) and MaxGuesses (zero is 5) set the factor's own. A code of more than 18 digits also stops Register, beyond the PHP package's bounds. OnePerUser keeps a user to one, a new one replacing the old. Never log the code: CodeRecipient's String hides its secret, which may hold a phone number.

A code factor counts as possession, so a password and a code are AAL2 and the first one comes with recovery codes. Its answers count under the configured limits: there's no limits() of its own, and no categories beyond possession or SentToAnAddress. See Code Factors.

SentToAnAddress 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. The contract app's text factor is one.

Beginning an enrollment of a code factor (POST /user/authenticators/{factor}) is limited by Limits.Forms, where the PHP package doesn't limit it. Its sends are limited per account alone, as in the PHP package: whoever is signed in chooses the number. If texts cost you money, limit them by number and by IP address in your Deliver too.

Deliver sends every code: at sign in, at step-up, and to confirm enrollment, when to.Enrolling is true. To send something that needs the sign in or step-up itself, such as a link to it, also implement keyring.SendsCodesFor[U], as overriding the PHP package's deliverFor() does. Its DeliverFor(ctx, attempt, user, to, code) then sends those two, and Deliver only the enrollment's. The keyring.CodeAttempt says which it is (Purpose, login or confirm), its ID, which every copy of the session shares, and when it ends (ExpiresAt). Emailed codes' sign-in link works this way. Add var _ keyring.SendsCodesFor[User] = (*sender)(nil) beside your sender, so a mistyped DeliverFor is a compile error rather than a method that's silently never called.

Collecting Details at Enrollment

A sender that also implements keyring.MakesCodeAuthenticators[U] collects something such as a phone number when the user adds the factor, as overriding newAuthenticator does. Whatever its NewAuthenticator 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 refuse it with a *web.InputError. 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

The PHP package lets you write any second factor of your own, and any factor that starts a sign in. Keyring for Go has the second kind, as primary factors: a code factor is the only second factor of your own so far.

Primary Factors

A primary factor starts a sign in by finding the user itself, such as a partner service's callback whose one-time token names the account. It's a keyring.PrimaryFactor[U], given something that implements keyring.IdentifiesUsers[U], to Keyring.AddPrimaryFactor. This is the contract app's partner factor, which signs in whoever a one-time token names:

Go
type Partners struct{} // Identify is whoever the token names, once: it's spent as it's read.func (Partners) Identify(r *web.Request, input map[string]any) (*keyring.Identified[models.User], error) {	token, _ := input["token"].(string)	id, ok, err := cache.Pull[int64](r, "partner:"+token)	if err != nil || !ok {		return nil, err	}	user, err := db.Table("users").Where("id", "=", id).First[models.User](r)	if _, missing := errors.AsType[*db.NotFoundError](err); missing {		return nil, nil	}	if err != nil {		return nil, err	} 	return &keyring.Identified[models.User]{User: &user}, nil} // Verify passes: the proof is who Identify found.func (Partners) Verify(*web.Request, *models.User, keyring.PrimaryAuthenticator, map[string]any) (bool, error) {	return true, nil} k := keyring.New[models.User]().AddPrimaryFactor(keyring.PrimaryFactor[models.User]{	Key: "partner", DefaultName: "Partner", Identifies: Partners{},	Categories: []string{keyring.Knowledge}, IdentifiedBy: []string{"token"},})

It signs in at POST /login/{key}, and with Keyring.Attempt(r, key) from a route of your own (see Starting a Sign In Yourself). Identify finds the user from what the request sent, and the row of the factor's own the request is aimed at with Identified.AuthenticatorID (or "" for none). Take the same time whether or not someone is found. Verify then checks the proof against that row, given as a PrimaryAuthenticator with its secret decrypted, and answers whether it holds. Use up anything single use there, so two requests with the same proof can't both pass.

The factor may also implement:

  • keyring.ValidatesSignIns: Validate checks the fields a sign in sent, refusing them with a *web.InputError. Keyring calls it before anything else, the rate limits included, so a missing field is answered alike whether or not the account is refused without saying so. Keyring doesn't validate the fields itself.
  • keyring.DiscoversUsers: LoginOptions gives the browser what it needs to start a sign in without a username, under options at GET /login/{key}/options, limited as the passkey's options are. Nil answers 404.
  • keyring.Stalls: Stall spends the time Verify would, when Keyring turns away whoever Identify found without looking at their proof (someone AllowSignInWhen keeps out, a row that isn't theirs) or a rate limit refuses without saying so.

Categories says what its proofs prove, and PhishingResistant and DeviceBound whether they're bound to the site's origin and to a device, once for the factor. IdentifiedBy lists the fields that name the user: a refused sign in is reported on the first, or on code with none. With Config.Username among them, its sign ins count under the typed name's and the account's limits, as the password's do (LockAfter and ClearAccount included); otherwise under the address's alone.

Each goes through what the password and passkeys go through: the pipeline with your steps, risk, the policy and the challenge, with the same events and log entries. Its proof is who it found, so it only ever starts a sign in: the challenge and confirm pages never ask for it, and users don't add it themselves. A row of a factor that proves Possession counts as a second factor the account has, which the challenge can't ask for, so give such rows only to accounts with another second factor. Register refuses a key that isn't lowercase letters, digits and dashes, that's one of Keyring's own or a code factor's (in any application in the process), or that's given twice, and a factor with no Identifies, DefaultName or category.

Optional Contracts

The PHP package's contracts, and what Keyring for Go has of them:

PHP Go
PrimaryFactor keyring.PrimaryFactor[U], given something that implements keyring.IdentifiesUsers[U], to Keyring.AddPrimaryFactor. See Primary Factors.
DiscoverableFactor keyring.DiscoversUsers, served at GET /login/{factor}/options.
Enrollable Code factors and Keyring's own factors only.
SendsCodes keyring.SendsCodes[U], given as a CodeFactor's Sender, and keyring.SendsCodesFor[U] for deliverFor().

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. k.SignInMethods(ctx, user) lists a user's as a settings page shows them. See Differences From PHP.

Factor Reference

Built-in Factors Table

Key Setting Categories Starts a Sign In Users Add It Priority
password None knowledge yes no 40
totp Factors.Totp* possession no yes 60
email-code Factors.EmailCodes, with .WithLink() for a sign-in link address (not a factor) no yes, one 30
recovery Factors.RecoveryCodes possession no yes, one set 0
passkey Factors.Passkeys possession, plus inherence when the user was verified yes yes 100
sso Factors.SingleSignOn knowledge yes, from the provider's callback yes, one per linked account 30

A code factor of your own has priority 30. When Keyring needs another factor, it offers the user's default authenticator first, then the rest by priority, then the oldest first.

Factor Methods

A code factor of your own is a struct, rather than a class with methods to override:

PHP Method Go
key CodeFactor.Key.
categories($authenticator) Possession, or the address with SentToAnAddress.
deliver(...) SendsCodes[U].Deliver.
deliverFor(...) SendsCodesFor[U].DeliverFor, which the sender may also implement.
newAuthenticator(...) MakesCodeAuthenticators[U].NewAuthenticator.
length, expireAfter, maxGuesses Length, ExpireAfter, MaxGuesses.
multiple() OnePerUser set for false.
priority 30, fixed.
limits($request, $attempt) Not available: answers count under the configured limits.
present($authenticator) Not available: every authenticator is presented as Keyring's are.