Signing InThe Sign In Flow

The Sign In Flow

On this page

Introduction

Signing in works as in the PHP package, with the same routes, JSON and status codes, held to it by the contract suite. The user proves a first factor, usually their password, by posting to /login. Keyring then asks the policy what else they need. If nothing, they're signed in. Otherwise Keyring saves a pending attempt in the session and sends them to the challenge page, repeating until the requirement is met.

A pending attempt lasts Config.PendingLogins, 10 minutes by default. It ends early if the user is gone, their password or address changes, or an authenticator it proved is taken off the account. Step-up uses the same challenge page and pipeline, with the purpose keyring.PurposeConfirm.

Signing In With a Password

Post email (or your Config.Username field) and password to /login, with an optional remember for "remember me". A wrong password and an unknown account get the same error on the username field, in at least Config.Timebox (500 milliseconds).

Finding the User

Keyring finds the user with the FindForLogin of your users, given the value after trimming and lowercasing it. By default that's Laravel Go's auth.ModelUsers[U], looking in the Config.Username column. Laravel Go doesn't let a package reach the users the application registered, so if yours are your own auth.Users[U], give them to Keyring as well:

Go
k := keyring.New[models.User]().FindUsersWith(users.Users{})

To sign in with an email address or a username, look up both in your FindForLogin. There's no Keyring::findUsersUsing(), and usernames are always normalised Keyring's way, for lookups, rate limits, email changes and reservations alike.

Who May Sign In

To keep an account out, such as a banned one, tell Keyring who may sign in:

Go
k.AllowSignInWhen(func(ctx context.Context, user *models.User) bool {    return user.BannedAt == nil})

Keyring asks it wherever a session starts or carries on: a password, a passkey alone, a pending login, "remember me", impersonation and each signed-in request. The first request it refuses signs the account out everywhere (not_allowed, SessionsRevoked), with its "remember me" cookies and trusted devices, and the account gets the same answer as one that doesn't exist. It runs on every signed-in request, so answer from the user you're given rather than with a query. k.AllowsSignIn(r, user) asks it from your own code, with a nil r outside a request.

Warning

Keyring only learns an account is kept out when one of its sessions makes a request. Sign the account out when you set the flag, as OWASP ASVS 5.0.0 (7.4.2) asks:

Terminal
go run . keyring:sign-out 42

There's no public way yet to sign a user out everywhere from your own code. See For Administrators.

A passkey alone loads its user with Find, not FindForLogin, as the PHP package does, so a user your FindForLogin hides still gets in with a passkey. AllowSignInWhen is where to keep them out of every factor.

Signing In With a Passkey

A passkey signs in without a username, in two requests, as in the PHP package. GET /login/passkey/options returns WebAuthn options under options, with no allowCredentials, and keeps the challenge in the session for WebAuthn.LoginOptionsFor. Then POST /login/passkey takes the browser's response as credential, and optionally remember. The options are limited to Limits.LoginOptions (60) a minute from one address. The browser package's usePasskeyLogin handles both (see Frontend). Both routes are a 404 while Factors.Passkeys is off.

Starting a Sign In Yourself

POST /login/{factor} starts a sign in with any factor that supports it: the password, a passkey, and primary factors of your own. When a proof arrives somewhere else, such as a callback from your own partner service, call Keyring.Attempt from your route, as Keyring::attempt():

Go
route.Post("/partner/callback", func(r *web.Request) *web.Response {	res, err := keyring.From[models.User](r).Attempt(r, "partner")	if err != nil {		return web.Fail(err)	} 	return res}).Middleware(keyring.Guest[models.User]{}, keyring.BlockSession{})

It runs the same pipeline as the login form, and answers as that route would: signed in, or on to the challenge (a 202 for JSON, a redirect to the challenge page for a browser). A refusal is the error, which web.Fail answers as Keyring's routes do: a 422 on the factor's field (the username for the password, credential for a passkey, a primary factor's first IdentifiedBy field), or a 429 for a lockout. "password" and "passkey" read what the request sent, as POST /login and POST /login/passkey do. A factor the application doesn't have, or that can't start a sign in, is a 404. Keyring.AttemptSSO(r, identity, remember) signs in whoever linked an identity provider's account (see Single Sign-On).

Put the route behind keyring.Guest and keyring.BlockSession, as Keyring's own are. A browser someone is already signed in on is sent on as Guest sends it, where the PHP package signs the new user in over them. A sign in half done in the browser is forgotten before the new one starts. Keep your own routes away from /auth/{provider}/..., which single sign-on uses.

Keyring.SignInAs signs in a user who just proved something outside the pipeline, as SignIn::as(): an account you've just created, with what creating it proved. Neither the policy nor risk runs, so never use it for an existing account.

Go
alerts, err := k.SignInAs(r, &user, []keyring.Proved{keyring.ProvedPassword()}, remember)

ProvedPassword() is the user's password, and ProvedAuthenticator(id) one of their sign-in methods by its ID, such as the link LinkNewAccount returns. Each counts as proved now, so as a fresh verification. Anything that isn't one of the user's own sign-in methods, or is of a factor the application doesn't have, is an error and signs nobody in. A user who may not sign in is refused as a wrong password, and leaves whoever was signed in on the browser signed in. It returns the "was this you?" alerts, which it also flashes as keyring.alerts.

The Challenge Page

GET /login/challenge shows the next factor. GET /login/challenge/{factor} shows that factor if it brings the user closer to the requirement. Without a pending login, a JSON request gets a 422 naming the login page.

Page Props

The props are the PHP package's, as the PHP docs describe: purpose, factor, authenticator, challenge, alternatives, canTrustDevice and expiresAt (RFC 3339). A passkey's challenge is {options}, and a code factor's {length, sent, expiresAt}.

Choosing an Authenticator

By default the page shows the user's default authenticator, or else the first useful one by priority. Add ?authenticator={id} to the factor's URL to pick a particular one, as in the PHP package.

Verifying

Post the proof to POST /login/challenge/{factor}, with the PHP package's fields: code, credential, an optional authenticator, and an optional trust. A wrong proof is a 422 on the factor's field, and the sign in can go on. The guess limits, timeouts and messages are the PHP package's, in English.

A wrong answer doesn't save the attempt, where the PHP package saves it. The guesses are counted on the server either way, and an attempt a wrong code leaves out of guesses is saved, so its page starts again.

Sending Codes

Code factors send a code only when asked, by posting to POST /login/challenge/{factor}/send, which answers code-sent. Viewing or prefetching the page sends nothing. It answers 404 for a factor that sends none. The limits are the PHP package's: three codes per factor every ten minutes in each of three buckets (Limits.Codes and Limits.CodesPer), and a fourth request in a bucket gets a 429 on code. The code goes out in the request, so a sender's error is the request's 500, with the new code already kept.

With EmailCodesAsExtraStep().WithLink(), the sign-in email also carries a link. Opened in the browser that started the sign in, its page posts the code to POST /login/challenge/email-code/link, which verifies it as POST /login/challenge/email-code would. Opened anywhere else, the page asks for the code from the email to be typed where the sign in started, without showing it.

Finishing the Login

When the requirement is met, Keyring does what the PHP package does: signs the user in with auth.Login (with "remember me" if ticked), moves the browser to a new session ID, records what they proved, recognises or registers the device and the session, dispatches Authenticated, answers the "was this you?" alerts, dispatches NewDeviceSignedIn if the device is new, and redirects to the intended URL or Config.Home. A JSON request gets 200 with {"status": "authenticated", "redirect": "...", "alerts": [...]}.

Where They Go Next

The intended URL is url.intended in the session, usually the page a guest was stopped on. Keyring only follows it on your app's own site, as in the PHP package. A path counts, made a full URL on the site. Anything else is dropped, and the user goes to Config.Home (/dashboard, or KEYRING_HOME).

Registration

POST /register passes the form to your CreatesNewUsers[U], given to Keyring with CreateUsersWith, with Features.Registration on. Its Validate checks the request and returns what Create needs, as a map. Passwords are in Unicode's NFC form before your action sees them. This is the contract app's, which follows the PHP package's CreateNewUser stub:

Go
package actions import (    "context"    "time"     "go.laravel.com/date"    "go.laravel.com/db"    "go.laravel.com/hash"    "go.laravel.com/validation"    "go.laravel.com/validation/rule"    "go.laravel.com/web"     keyring "keyringauth.com/go"     "app/models") type CreateNewUser struct{} type registration struct {    Name     string `json:"name"`    Email    string `json:"email" transform:"lowercase"`    Password string `json:"password"`} // Rules checks the form, with Keyring's password rules. There's no user// yet, so the name and address given count as theirs.func (f *registration) Rules(r *web.Request) (validation.Rules, error) {    passwords, err := keyring.From[models.User](r).PasswordRules(r, nil)    if err != nil {        return validation.Rules{}, err    }     return validation.For(f,        rule.Field(&f.Name, rule.Required, rule.Max(255)),        rule.Field(&f.Email, rule.Required, rule.Email, rule.Max(255)),        rule.Field(&f.Password, passwords.Context(f.Name, f.Email)),    ), nil} func (CreateNewUser) Validate(r *web.Request) (map[string]any, error) {    form, err := r.Validate[registration]()    if err != nil {        return nil, err    }     return map[string]any{"name": form.Name, "email": form.Email, "password": form.Password}, nil} func (CreateNewUser) Create(ctx context.Context, input map[string]any) (*models.User, error) {    name, _ := input["name"].(string)    email, _ := input["email"].(string)    password, _ := input["password"].(string)     hashed, err := hash.Make(ctx, password)    if err != nil {        return nil, err    }     now := date.Now(ctx).UTC().Truncate(time.Second)    id, err := db.Table("users").InsertGetID(ctx, db.Values{        "name": name, "email": email, "password": hashed, "created_at": now, "updated_at": now,    })    if err != nil {        return nil, err    }     return &models.User{ID: id, Name: name, Email: email, Password: &hashed, CreatedAt: &now, UpdatedAt: &now}, nil}
Go
k := keyring.New[models.User](func(cfg *keyring.Config) {    cfg.Features.Registration = true    cfg.Features.EmailVerification = true}).CreateUsersWith(actions.CreateNewUser{})

PasswordRules is the PHP package's password rules (see Password Rules). Create returns the user as stored, with their ID, address and password hash, which Keyring reads to mail the link and to sign them in.

Don't check whether the address is free yourself. Keyring does that after Validate and before Create, reading the address from what Validate returned under Config.Email: an address counts as taken when the users table has it in the Config.Email column (whoever you keep from signing in, as the PHP package looks without global scopes), when it's held for its previous owner during an email change, or when the insert breaks a unique index. For users that aren't Laravel Go models, implement keyring.TakenAddresses on the action, a Taken(ctx, email) (bool, error), and Keyring asks it instead. PasswordRules also refuses a password bcrypt would cut short or can't take (over 72 bytes, or a NUL), so use it as the password's only rule.

Create runs in a database transaction of Keyring's own. If a unique index refuses it, Keyring looks for the address again: taken by then, it's answered as taken, and otherwise it's an error like any other.

Without Revealing Who Has an Account

By default (Registration.RevealTaken is false), the form never shows whether an address has an account, as OWASP ASVS 5.0.0 (6.3.8) asks, and as the PHP docs describe. Every address gets 200 { "status": "registration-received", "message", "page": "login", "redirect" }, in at least Config.Timebox, nobody is signed in, and the emails go out after the answer, off the request: a new user's verification link, another link to an account that was never verified, or the already_registered email to a taken address.

The already_registered email goes to the address the account has, and only when that's the address typed once both are normalised, stricter than the PHP package, which mails the typed address. On a collation that ignores accents, a typed lookalike would otherwise learn another address is registered.

A new user can't sign in until their address is verified, so a right password is refused as a wrong one. That gate follows the PHP package's: it's on whenever registration is on and hides who has an account. A Go app sharing users with a PHP app that registers should turn registration on too, so both hold unverified users back. Email verification must be on: registration that hides who has an account without it stops Register.

Saying When an Address Is Taken

Go
cfg.Registration.RevealTaken = true

A taken address is a 422 "has already been taken" on email, beside the form's other errors, and a new user is signed in straight away, with their password counting as proved, answering as a sign in does.

Warning

This tells anyone who asks whether an address has an account, through the error and through being signed in. It doesn't meet ASVS 6.3.8.

A new user your AllowSignInWhen keeps out, for example until an admin approves them, isn't signed in. They get the registered status, naming the login page. There's no separate signInAfterRegistering().

Registered[U] is dispatched for a new user either way. It's Keyring's own event, since Laravel Go has none.

Signing Out

POST /logout ends the registered session, signs the user out and moves the browser to a new session. JSON clients get 204 No Content, and everyone else is redirected to /. The response sends Clear-Site-Data: "cache", "storage" and leaves cookies alone, so the device survives. LoggedOut[U] is dispatched.

Signing out uses Laravel Go's auth.Logout, which gives the user a new remember token, so their other remembered browsers are signed out too. The PHP package signs only this browser out. See Signing In and Out.

There's no SignIn::out() to call from your own code. Call auth.Logout(r) on a route inside AuthenticateSession (any route in the web group): Keyring notices the session's record leaving once the handler returns, and ends it.

The Verification Pipeline

Every verification, at login or step-up, runs through the PHP package's steps, in the same order: EnsureNotThrottled, VerifyFactor, ResolveDevice, EnsureNotRiskLocked, AssessRisk, DetermineRequirement and CompleteAttempt. What each does is in the PHP docs. Their names are constants: keyring.StepResolveDevice, keyring.StepAssessRisk and the rest.

EnsureNotThrottled, VerifyFactor and CompleteAttempt are fixed places in Keyring's code, wrapped around the others. The steps you can see and change are the four between them, and yours go between them too.

Customising the Steps

Change the pipeline with Pipeline, as Keyring::pipeline(). Your function gets the steps as they are and returns them changed. This adds a step after ResolveDevice and replaces AssessRisk:

Go
k.Pipeline(func(steps keyring.Steps[models.User]) keyring.Steps[models.User] {    return steps.        After(keyring.StepResolveDevice, RefuseGuestNetwork{}).        Replace(keyring.StepAssessRisk, StrictRisk{})})

Before, After, Replace and Remove take a step's name: Keyring's are the Step* constants, and yours is its type's name without its package, unless it has a Name() string method. A step that isn't there, or a step placed before VerifyFactor or after CompleteAttempt, stops Register with the reason. k.StepNames() lists the steps in order. Call Pipeline before Register: it panics after.

Mandatory Steps

EnsureNotRiskLocked and DetermineRequirement are mandatory: Replace and Remove refuse them, stopping Register. DangerouslyReplace and DangerouslyRemove change them anyway, as in the PHP package:

Go
k.Pipeline(func(steps keyring.Steps[models.User]) keyring.Steps[models.User] {    return steps.DangerouslyReplace(keyring.StepDetermineRequirement, MyRequirement{})})

Warning

Dangerous changes log a warning as Keyring registers, and k.DangerouslyChangedSteps() lists them, for a test to acknowledge: the conformance suite fails until AcknowledgedDangerousSteps lists them.

Go
keyringtest.Conformance[models.User]{    // App, User, ...    AcknowledgedDangerousSteps: []string{keyring.StepDetermineRequirement},}.Run(t)

EnsureNotThrottled, VerifyFactor and CompleteAttempt can't be changed, even dangerously. A verification that would complete without a mandatory check having run, when that step wasn't dangerously changed, is refused with VerificationRefused and a critical verification_refused entry. A replacement that does the risk lock check itself sets c.RiskLockChecked, using k.IsRiskLocked(r, c.User).

With DetermineRequirement dangerously removed or replaced, Keyring still refuses an account with a factor it can't check, stricter than the PHP package, where that refusal goes with the step.

Writing a Step

A step implements keyring.Step[U]: a Handle(r *web.Request, c *keyring.StepContext[U]) error. Call c.Fail() to refuse the verification, or return an error to fail the request with it:

Go
// RefuseGuestNetwork refuses verifications from the guest network.type RefuseGuestNetwork struct{} func (RefuseGuestNetwork) Handle(r *web.Request, c *keyring.StepContext[models.User]) error {    if r.Header.Get("X-Network") == "guest" {        c.Fail()    }     return nil}

The context holds User, Factor (the key), Identifying (true for a sign in's first factor), Attempt (the attempt as the policy sees it, with Purpose), Requirement (once DetermineRequirement has run) and RiskLockChecked. There's no authenticator, verification or outcome on it.

c.Fail() refuses the verification as a wrong proof is refused, counting toward the rate limits but without FactorFailed. There's no $context->lockout(). Every verification runs the steps: a password, a passkey alone, each answer on the challenge page and each confirm. So a step that should act once per sign in checks the attempt itself, as AssessRisk does (c.Attempt.Purpose == keyring.PurposeLogin && c.Attempt.Risk == nil). A step that runs its own risk check sets c.Attempt.Risk and c.Attempt.StepUp before DetermineRequirement, and k.AssessmentOf(r, c) gives it the risk assessment for the request. A step that replaces ResolveDevice notes the device with c.Attempt.ResolveDevice(device), found with k.FindDevice(r, c.User).

ResolveDevice doesn't note "don't ask again on this device" in Go: that stays with the form that sent trust, so replacing the step doesn't lose it.

The contract app's policies package has a step of its own, RefuseBlocked, placed after ResolveDevice.

Responses

Each outcome is answered as the PHP package's response contracts answer it, as its docs describe: authenticated, registered, the challenge's 202, the confirm's 423, enroll-first, change-password, signed-out, the logout's 204 and the status responses. "JSON" means the request expects JSON and isn't an Inertia visit.

They can't be replaced: there's no respondWith(). A refused sign in or step-up is a Laravel Go validation error, *web.InputError, a lockout's wrapped to answer 429: render it your own way with Laravel Go's error handling. A browser's refusal on fields is given a 422, so Laravel Go redirects it back with the errors and the input, whatever status a JSON client gets. See Pages and Responses.

Status Responses

Every action that isn't a sign in or confirmation answers with a status response, with the PHP package's slugs, messages and data. A JSON request gets {status, message, ...data}. Other requests are redirected back, with the slug flashed as status, and the data flashed as JSON under keyring.result, encrypted with crypt.EncryptString whatever the session driver. keyring.FlashedResult(r) reads it on the next request, and keyring.StatusMessage(slug) gives a slug's message:

Go
result := keyring.FlashedResult(r) // such as {"recoveryCodes": [...]}, or nilmessage, ok := keyring.StatusMessage("authenticator-added")

See Flash Messages and Alerts for sharing both with every page.

Pages

Keyring renders the PHP package's pages, with the same props: login, challenge, confirm, register, forgot-password, verify-email, reset-password, email-verification, email-change, device-report and sign-in-link. The props are in the PHP docs, and sign-in-link's in Signing In From the Email.

Each page is the Inertia component auth/{name}, such as auth/login, rendered with Laravel Go's inertia.Render. Add inertia.Middleware{} to the web group, as the contract app does, so an Inertia visit gets a page object. There are no Blade-style views.

A JSON request for a page gets {"page": name, "props": {...}} instead, as in the PHP package. With Config.Pages off, anything but JSON gets a 404.

A page's component can't be renamed, and there's no way to render a page your own way or to render one of Keyring's from a route of your own. Name your components auth/{name}, or turn Config.Pages off and serve the pages from your own frontend. See Pages and Responses.

Routes

The paths and names are the PHP package's. They go in the web group, under Config.Prefix (empty by default). Turn Config.Routes off to place them yourself with k.Routes(route).

Method URI Name Purpose
GET /login login The login page.
POST /login login.store Sign in with a password.
GET /login/passkey/options keyring.login.options Options for a sign in without a username.
GET /login/{factor}/options Options for a sign in with a primary factor of your own that gives some (DiscoversUsers).
POST /login/{factor} keyring.login.factor Sign in with a passkey, or a primary factor of your own.
GET /auth/{provider}/redirect keyring.sso.redirect Sends the user to an identity provider. See Single Sign-On.
GET /auth/{provider}/callback keyring.sso.callback Where the provider sends the user back.
GET /confirm/sso/redirect keyring.sso.confirm Sends a signed-in user to the provider for a step-up.
GET /login/challenge/{factor?} keyring.login.challenge The challenge page.
POST /login/challenge/{factor} keyring.login.verify Verifies the next factor.
POST /login/challenge/{factor}/send keyring.login.send Sends a code.
GET /login/challenge/email-code/link keyring.login.link The page an emailed code's sign-in link opens, for any browser, signed in or not. Only there while EmailCodes.Link is on.
POST /login/challenge/email-code/link keyring.login.link.store That page's button: verifies the code, in the browser that started the sign in. Only there while EmailCodes.Link is on.
GET /register register The registration page.
POST /register register.store Creates an account.
POST /logout logout Signs out.

GET /login/{factor}/options is routed for each primary factor of your own that gives options, under Limits.LoginOptions as the passkey's are, and is a 404 when the factor has nothing to give. Any other factor's is a 404.

The registration routes exist only when Features.Registration is on, and POST /register is limited to Limits.GuestForms (six a minute per address). The routes that spend session state take the session lock (keyring.BlockSession), as ->block() does in the PHP package, so parallel requests wait their turn: 10 seconds to hold and 10 to wait. A request that waits the full 10 seconds gets a 500, not a 423.

Note

Your default cache store must support locks.

A signed-in browser at a guest page (/login, /register, the challenge page and the rest, but not the sign-in link's page, which answers any browser) is redirected where the PHP package's guest middleware sends it: the route named dashboard, else the one named home, else the site's root. Laravel Go has no redirectUsersTo(), so name the route you want dashboard.

Events

The events are the PHP package's, dispatched where the PHP package dispatches them: Attempting, FactorChallenged, FactorVerified, ProviderIdentityAccepted, FactorFailed, Lockout, VerificationRefused, AccountLocked, Authenticated, Confirmed, LoggedOut and SessionEnded, plus Registered and Verified. Most are generic over your user type, as keyring.Authenticated[models.User]. They carry plain values rather than the request: FactorFailed has the Username that was typed, and Attempting the factor. See Events.

Laravel's own Login, Logout, Failed and Lockout events aren't dispatched, as Laravel Go has none of them.