# The Sign In Flow

Source: https://keyringauth.com/docs/0.x/sign-in-flow

## Introduction

Signing in takes three steps. The user proves a first factor, usually their password, by posting to `/login`. Keyring then asks the [policy](https://keyringauth.com/docs/0.x/policies) 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 `pending_logins.keep_for`, 10 minutes by default. It ends early if the user's password or email address changes, so a reset also stops someone who got past the old password. [Step-up](https://keyringauth.com/docs/0.x/step-up) uses the same challenge page and pipeline, with the purpose `confirm`.

## Signing In With a Password

Post `email` (or your `username` attribute) and `password` to `/login`, with an optional `remember` for Laravel's "remember me" cookie. Keyring reads them from the body, as a form or as JSON, and ignores the query string. A wrong password and an unknown account get the same `auth.failed` error on the username field, in the same time.

### Finding the User

Keyring finds the user by the `username` option, which is `email` by default, after trimming and lowercasing the value. Change either in your `KeyringServiceProvider`:

```php
use App\Models\User;
use Illuminate\Http\Request;

// Sign in with an email address or a username.
Keyring::findUsersUsing(fn (Request $request) => User::query()
    ->where('email', $request->email)
    ->orWhere('username', $request->email)
    ->first());

// Keep usernames' case (for lookups, rate limits, email changes and reservations).
Keyring::normalizeUsernamesUsing(fn (string $username) => trim($username));
```

Case sensitivity depends on your database: MySQL's default collations ignore case, PostgreSQL and SQLite don't. Failed attempts count against the user the finder returns, however the username was typed. Keyring calls the finder twice per attempt, so keep it a simple lookup. The finder only finds the user. Keyring still checks the password, and a `null` result gets the same answer as a wrong password.

### Who May Sign In

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

```php
use App\Models\User;

Keyring::allowSignInWhen(fn (User $user) => ! $user->banned);
```

Keyring checks it when a sign-in starts, when a sign-in continues, and on every request in a signed-in session.

A refused session is signed out with a `session_ended` entry (reason `not_allowed`). The account's other sessions, cookies, trusted devices and pending email change are ended too, with a `sessions_revoked` entry. The account gets the same answer as one that doesn't exist. Password resets and the links that confirm or undo an email change still work. The callback runs on every signed-in request, so answer from the user it receives rather than running a query.

> [!WARNING]
> Keyring only learns an account is kept out when one of its sessions makes a request. Until then, those sessions would work again if the account were let back in first. Sign the account out when you set the flag. OWASP ASVS 5.0.0 (7.4.2) also asks for this:

```php
use Keyring\Sessions\Sessions;

$user->forceFill(['banned' => true])->save();

app(Sessions::class)->signOutEverywhere($user);
```

> [!WARNING]
> Don't use a global scope on the user model to keep an account out. Keyring sees the account as missing and ends nothing, so its sessions and cookies survive when the scope lifts.

## Signing In With a Passkey

A passkey signs in without a username, in two requests. `GET /login/passkey/options` returns WebAuthn options under `options`, with an empty `allowCredentials`, and keeps the challenge in the session. Then `POST /login/passkey` takes the browser's response as `credential`, and optionally `remember`. The `GET` answer looks like this:

```json
{ "options": { "challenge": "...", "timeout": 60000, "rpId": "example.com", "allowCredentials": [], "userVerification": "required" } }
```

The same options power autofill when the email field has `autocomplete="username webauthn"`. The browser package's `usePasskeyLogin` handles both (see [Frontend](https://keyringauth.com/docs/0.x/frontend#signing-in-with-a-passkey)). The passkey still goes through the policy, and [Laravel's Passkeys Client](https://keyringauth.com/docs/0.x/passkeys#laravels-passkeys-client) can use these routes too. Security keys can't start a sign-in, so their routes return `404`.

## Starting a Sign In Yourself

`POST /login/{factor}` starts a sign-in with any factor that supports it. When a proof arrives somewhere else, such as a callback from your own partner service, call `Keyring::attempt` from your route:

```php
use Illuminate\Http\Request;
use Keyring\Facades\Keyring;

Route::get('/partner/callback', fn (Request $request) => Keyring::attempt($request, 'partner'))
    ->middleware('guest')
    ->block();
```

It runs the same [pipeline](https://keyringauth.com/docs/0.x/sign-in-flow#the-verification-pipeline) as the login form. A failure throws a `ValidationException`, which you may want to turn into a redirect. Keep your own routes away from `/auth/{provider}/...`, which [single sign-on](https://keyringauth.com/docs/0.x/sso) uses.

## 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. With no pending attempt, the user goes back to the login page.

### Page Props

The page (`challenge` for sign-ins, `confirm` for step-up) receives props like these:

```json
{
  "purpose": "login",
  "factor": "security-key",
  "authenticator": { "factor": "security-key", "id": "01JC3...", "name": "Work key" },
  "challenge": { "options": { "challenge": "...", "rpId": "example.com", "allowCredentials": [{ "type": "public-key", "id": "AbC...", "transports": ["usb"] }] } },
  "alternatives": [
    { "factor": "totp", "id": "01JC4...", "name": "Authenticator app" },
    { "factor": "recovery", "id": "01JC5...", "name": "Recovery codes", "remaining": 7, "replace": false }
  ],
  "canTrustDevice": true,
  "expiresAt": "2026-11-08T14:05:00+00:00"
}
```

| Prop | |
|---|---|
| `purpose` | `login` or `confirm`. |
| `factor` | The key of the factor to verify now. |
| `authenticator` | `factor`, `id` and `name` (`id` is `null` for the password). Email codes add `hint`, a masked address. Recovery codes add `remaining`, and `replace` is true once a code is used, so the user should [make a new set](https://keyringauth.com/docs/0.x/authenticators#recovery-codes). |
| `challenge` | Props for the factor. See below. |
| `alternatives` | The user's other authenticators that would help, in the same shape. |
| `canTrustDevice` | Whether to offer "don't ask again on this device": sign-ins only, when `Features::devices()` is on, `devices.trust_for` isn't `null`, and this factor would bring the sign-in to AAL2. |
| `expiresAt` | When the attempt expires, as an ISO 8601 date. |

For built-in factors, `challenge` holds: nothing for `password`, `totp` and `recovery` (`[]`); `length`, `sent` and `expiresAt` for `email-code`; `options` for `passkey` and `security-key`; and, on the confirm page only, `provider`, `label` and `url` for `sso` (see [Single Sign-On](https://keyringauth.com/docs/0.x/sso#step-up)).

Alternatives only include authenticators that get the user closer to the requirement. With [no downgrade](https://keyringauth.com/docs/0.x/policies#no-downgrade), an established key user is offered only their other keys, plus recovery codes.

### Choosing an Authenticator

By default the page shows the user's default authenticator, or else the first useful one by priority. To pick a particular authenticator, add `?authenticator={id}` to the factor's URL, such as `/login/challenge/security-key?authenticator={id}`. Keyring remembers the choice for each factor.

### Verifying

Post the proof to `POST /login/challenge/{factor}`:

| Field | Used By |
|---|---|
| `password` | `password` |
| `code` | `totp`, `email-code`, `recovery` and most custom factors. |
| `credential` | `passkey` and `security-key`: the WebAuthn response, as an object or a JSON string. Any of the user's keys for that factor is accepted. |
| `authenticator` | Optional. Defaults to the one shown, or to the only one of that factor. |
| `trust` | Optional boolean. Trusts the device for `devices.trust_for` once the login reaches AAL2. |

A wrong proof fails with `keyring::keyring.invalid` on the factor's field. A wrong code keeps its guess count, so reloading or resending doesn't reset it.

Once an attempt reaches a factor's guess limit (five by default), verifying fails with `keyring::keyring.too_many_codes`, and the attempt can't be finished. Opening the challenge page or sending a code ends it and sends the user back to the start with that message: on the username field at `/login`, and on the field of the factor asked next at `/confirm`. A timed-out attempt gets `keyring::keyring.expired`. A JSON request that's sent back to the start gets these as a `422` with `page` and `redirect` added.

### Sending Codes

Code factors send a code only when asked, by posting to `POST /login/challenge/email-code/send`. Viewing or prefetching the page sends nothing. An account can be sent three codes per factor every 10 minutes ([`limits.codes` and `limits.codes_per`](https://keyringauth.com/docs/0.x/configuration#pending-logins-timebox-and-rate-limits)), in each of three buckets: sign-ins from browsers that never signed in to the account, sign-ins from browsers that did, and step-ups and enrollments. So sign-ins started from unknown browsers can't use up the owner's, and the account is sent at most nine per factor in that time ([Rate Limiting](https://keyringauth.com/docs/0.x/security#rate-limiting)). A fourth request in a bucket gets a `429` on `code`. A new code replaces the last, and a code only verifies the authenticator it was sent to. The response is a `code-sent` [status response](https://keyringauth.com/docs/0.x/sign-in-flow#status-responses).

With [`EmailCode::asExtraStep()->withLink()`](https://keyringauth.com/docs/0.x/factors#signing-in-from-the-email), 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:

1. signs the user into the guard, with "remember me" if ticked,
2. regenerates the session ID, destroying the old one,
3. records what they proved, for [step-up](https://keyringauth.com/docs/0.x/step-up),
4. recognises or registers the [device](https://keyringauth.com/docs/0.x/devices-and-sessions), and registers the session,
5. dispatches `Keyring\Events\Authenticated`,
6. flashes `keyring.alerts` for suspicious activity since the last sign-in, and includes them as `alerts` in JSON (see ["Was This You?" Alerts](https://keyringauth.com/docs/0.x/security-log-and-emails#was-this-you-alerts)),
7. dispatches `NewDeviceSignedIn` if the device is new,
8. redirects to the intended URL, or `home`. A JSON request gets `200` with `{"status": "authenticated", "redirect": "...", "alerts": [...]}`.

### Where They Go Next

The intended URL is Laravel's `url.intended`, usually the page a guest was stopped on. Anyone can send a `Referer`, so Keyring only follows an intended URL on your app's own origins: the request's, `APP_URL`'s and the [`domain` option](https://keyringauth.com/docs/0.x/configuration#routes)'s host, each with its scheme and port. A path such as `/billing` on the request's host is fine too. Anything else, like `https://elsewhere.example` or `//elsewhere.example`, is dropped, and the user goes to `home`. The same rule applies to JSON `redirect`s and to the other redirects Keyring makes after a sign-in.

## Registration

`POST /register` passes the request to your `CreatesNewUsers` action, published to `app/Actions/Keyring/CreateNewUser.php` and registered with `Keyring::createUsersUsing`. Its `validate(array $input)` method checks the form and returns what `create(array $input)` needs. The published version uses `PasswordRules::for`. See [Password Rules](https://keyringauth.com/docs/0.x/protected-changes#password-rules).

Don't check whether the address is free yourself. Keyring does that after `validate` and before `create`. An address counts as taken when an account has it, including a soft-deleted one, or when it's [held for its previous owner](https://keyringauth.com/docs/0.x/protected-changes#the-old-address-is-reserved) during an email change. `registration.reveal_taken` decides what happens then. A unique field of your own, such as a handle, still reveals when it's taken, because your action checks it.

### Without Revealing Who Has an Account

By default (`registration.reveal_taken` is `false`), the form never shows whether an address has an account, as OWASP ASVS 5.0.0 (6.3.8) asks.

- The answer is always the login page with the `registration-received` status, or that status as JSON. Nobody is signed in.
- Validation errors are the same for every address, since your action never checks for a taken one.
- Keyring refuses any password the hasher can't handle, such as one over 72 bytes with bcrypt.
- A free address gets its account, and Laravel's `Registered` event emails the verification link after the response.
- A taken address gets nothing created. Keyring emails the `already_registered` [notification](https://keyringauth.com/docs/0.x/security-log-and-emails#emails-a-flow-needs) instead, which links to login and, with `Features::resetPasswords()`, to the forgot password page. If that account was never verified, it gets a new verification link instead.
- Each address gets five registration emails an hour at most (`limits.notices`), and past that nothing is sent. Every request takes at least `timebox` (500ms), and the `keyring.throttle` middleware, which uses the `keyring` rate limiter, allows six a minute per IP.
- If `create` throws, Keyring reports the exception and gives the usual answer. Nothing is created.

A new user can't sign in until their address is verified. Otherwise anyone could register an address and learn it was free. So until then, a correct password gets the same answer as a wrong one.

Verifying takes the emailed link and the password together. Following the link, while signed out, sends the user to the login page with `sign-in-to-verify`. A JSON request gets a `401` with `{"status": "sign-in-to-verify", "message": "...", "page": "login", "redirect": "..."}`. Keyring gives the session a new ID first, so only this browser holds the link. Opening the link alone verifies nothing, so a mail scanner can't verify an address. Signing in from that browser does, and fires Laravel's `Verified` event. The link works for `auth.verification.expire` (60 minutes). A finished [password reset](https://keyringauth.com/docs/0.x/protected-changes#resetting-the-password) verifies the address too, even where registration hides who has an account, since its link goes to the same inbox.

Email verification must be on. With registration on and `Features::emailVerification()` off, the app won't boot (`Keyring\Exceptions\EmailVerificationRequired`). A user model without `MustVerifyEmail`, or no `already_registered` notification, makes `POST /register` throw before saving.

An unverified account can't sign in, and a session whose user loses `email_verified_at` is signed out on its next request. Mark accounts you create yourself, through an import, a seeder or a social login, as verified.

### Saying When an Address Is Taken

To tell people straight away that an account exists, set the option, and registration works like Laravel's starter kits:

```php
// config/keyring.php
'registration' => [
    'reveal_taken' => true,
],
```

A taken address gets Laravel's "has already been taken" error on the email field, and nothing is emailed. A new user is signed in straight away, with their password counting as proved, and the policy isn't consulted. The answer comes from `RegisterResponse`. Email verification is optional in this mode.

> [!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.

To keep new users signed out, for example until an admin approves them, pass `false` or a callback to `signInAfterRegistering`. They go to the login page with the `registered` status:

```php
Keyring::signInAfterRegistering(fn (User $user, Request $request) => ! $user->needs_approval);
```

## Signing Out

`POST /logout` revokes the registered session, signs the user out and invalidates the 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 and the next sign-in isn't a new device.

From your own code, call `out` on `Keyring\Login\SignIn`. It returns the user who was signed out, or `null`. `Auth::logout()` on Keyring's guard ends the registered session too, so an existing sign-out route keeps working, but invalidate the session afterwards as Laravel's docs say. `out()` does that part for you:

```php
use Keyring\Login\SignIn;

app(SignIn::class)->out($request);
```

Neither dispatches `LoggedOut`. Dispatch `Keyring\Events\LoggedOut` yourself if you want it in the security log.

## The Verification Pipeline

Every verification, at login or step-up, runs through these steps:

| Step | Does |
|---|---|
| `EnsureNotThrottled` | Checks the factor's rate limits and locks out repeated failures. See [Rate Limiting](https://keyringauth.com/docs/0.x/security#rate-limiting). |
| `VerifyFactor` | Validates the request, identifies the user for primary factors and checks the proof. A failure stops the pipeline. |
| `ResolveDevice` | Notes the device, and the `trust` checkbox. |
| `EnsureNotRiskLocked` | Refuses a user under a [risk lock](https://keyringauth.com/docs/0.x/risk#actions). Skipped for step-up. |
| `AssessRisk` | Runs the [risk signals](https://keyringauth.com/docs/0.x/risk) once per login. Skipped for step-up. |
| `DetermineRequirement` | Asks the policy what the user must prove. |
| `CompleteAttempt` | Signs the user in or confirms them when the requirement is met. Otherwise it saves the attempt for the challenge page. |

### Customising the Steps

Change the pipeline with `Keyring::pipeline`. This adds a step after `ResolveDevice` and replaces `AssessRisk`:

```php
use App\Keyring\BlockSanctionedCountries;
use App\Keyring\MyRiskStep;
use Keyring\Facades\Keyring;
use Keyring\Pipeline\Steps;
use Keyring\Pipeline\Steps\AssessRisk;
use Keyring\Pipeline\Steps\ResolveDevice;

Keyring::pipeline(fn (Steps $steps) => $steps
    ->after(ResolveDevice::class, BlockSanctionedCountries::class)
    ->replace(AssessRisk::class, MyRiskStep::class));
```

`Steps` has `before`, `after`, `replace` and `remove`, and each throws an `InvalidArgumentException` for a step that isn't in the pipeline. Callbacks run as you call `Keyring::pipeline`, so mistakes show at boot.

### Mandatory Steps

`EnsureNotThrottled`, `VerifyFactor`, `EnsureNotRiskLocked`, `DetermineRequirement` and `CompleteAttempt` enforce Keyring's guarantees. `replace` and `remove` throw for them. You may change `ResolveDevice` and `AssessRisk`. To take out a mandatory step anyway, use `dangerouslyReplace` or `dangerouslyRemove`:

```php
Keyring::pipeline(fn (Steps $steps) => $steps
    ->dangerouslyReplace(EnsureNotThrottled::class, MyRateLimiter::class));
```

> [!WARNING]
> `dangerously` methods log a warning, and the [conformance suite](https://keyringauth.com/docs/0.x/testing#the-conformance-suite) fails until you acknowledge the step. What it checked is then up to you.

Before signing anyone in, `CompleteAttempt` checks that the request was throttled, verified and checked for a risk lock, and that the requirement is met. If not, it dispatches `VerificationRefused` (a `verification_refused` entry in the [security log](https://keyringauth.com/docs/0.x/security-log-and-emails#entry-types)) and refuses.

### Writing a Step

A step has a `handle()` method that receives a `Keyring\Pipeline\Context` and the next step. Steps are resolved from the container:

```php
namespace App\Keyring;

use Closure;
use Keyring\Devices\Location;
use Keyring\Enums\Purpose;
use Keyring\Pipeline\Context;

class BlockSanctionedCountries
{
    public function handle(Context $context, Closure $next): Context
    {
        $country = Location::of($context->request)['country'] ?? null;

        if ($context->purpose === Purpose::Login && in_array($country, config('app.blocked_countries'), true)) {
            return $context->fail();
        }

        return $next($context);
    }
}
```

The context holds `request`, `purpose` (`Purpose::Login` or `Purpose::Confirm`), `factor`, `attempt`, `authenticator`, `verification` (set once `VerifyFactor` passes), `identifying` (true for a sign-in's first factor) and `outcome`.

`Location::of($request)` looks up the [locator](https://keyringauth.com/docs/0.x/devices-and-sessions#locations) once per request. Return `$context->fail()` for the generic password error, which counts toward the rate limits like a wrong password. `$context->lockout($seconds)` answers as rate limited. Before `VerifyFactor`, `attempt` is `null` for a first factor.

## Responses

Each outcome is answered by a response class, bound to a contract in `Keyring\Contracts\Responses`:

| Contract | When | Default |
|---|---|---|
| `AuthenticatedResponse` | Login or confirmation is complete. | Redirects to the intended URL or `home`. JSON: `{"status": "authenticated", "redirect": "...", "alerts": [...]}`, without `alerts` after a confirm. A response of your own reads them from `$request->attributes->get('keyring.alerts')`. |
| `ChallengeResponse` | Another factor is needed. | Redirects to the challenge page. JSON: `202` with `{"status": "challenge", "page": "challenge", "redirect": "..."}`. `page` is `confirm` for step-up. |
| `FailedResponse` | The proof was wrong, or the user wasn't found. | `auth.failed` on the username field for a password login (a passkey sign-in has no username field, so it goes on `credential`), otherwise `keyring::keyring.invalid` on the factor's field. |
| `LockoutResponse` | Too many attempts. | A `429` with `auth.throttle`, `keyring::keyring.locked` when a password reset is the way back in, or `keyring::keyring.factor_locked` for a factor that must be set up again. |
| `LogoutResponse` | The user signed out. | Redirects to `/`. JSON: `204`. |
| `RegisterResponse` | A new user is signed in by [`registration.reveal_taken`](https://keyringauth.com/docs/0.x/sign-in-flow#saying-when-an-address-is-taken). | As `AuthenticatedResponse`. |
| `StatusResponse` | Every other action. | See [Status Responses](https://keyringauth.com/docs/0.x/sign-in-flow#status-responses). |
| `SignedOutResponse` | The session was ended: revoked, timed out, ended by risk, or an [impersonation](https://keyringauth.com/docs/0.x/impersonation#security-log-and-events) with nothing to return to. | Redirects to login with `signed-out`. JSON: `401` with `"page": "login"` and `redirect`. Not used for page visits on [routes that also serve guests](https://keyringauth.com/docs/0.x/devices-and-sessions#pages-that-also-serve-guests); JSON requests there still get the `401`. |
| `SignInToVerifyResponse` | A verification link was opened while signed out, under [hidden registration](https://keyringauth.com/docs/0.x/sign-in-flow#without-revealing-who-has-an-account). | As in that section. |
| `ConfirmationRequiredResponse` | A route needs [step-up](https://keyringauth.com/docs/0.x/step-up). | Redirects to the confirm page. JSON: `423` with `"page": "confirm"` and `redirect`. |
| `EnrollmentRequiredResponse` | A route needs a sign-in method the user hasn't set up. | Redirects to `enrollment_url` with `enroll-first`, or `403`. JSON: `403`. |
| `PasswordChangeRequiredResponse` | The user must [choose a new password](https://keyringauth.com/docs/0.x/protected-changes#requiring-a-password-change). | Redirects to `password_change_url` with `change-password`, or `403`. JSON: `403`. |
| `VerifiedResponse` | The email address is verified. `justNow` is true when the link did it. | Redirects to the intended URL or `home`, with `?verified=1` when `justNow`. JSON: `{"status": "email-verified", "message": "...", "justNow": true, "redirect": "..."}`. |

"JSON" means the request expects JSON and isn't an Inertia request. When a JSON answer redirects to one of Keyring's [pages](https://keyringauth.com/docs/0.x/sign-in-flow#pages), it also names it as `page`, so a [frontend of your own](https://keyringauth.com/docs/0.x/headless) needn't parse the URL.

A sign in or step-up that ran out, or used up its guesses, sends a JSON request a `422` in Laravel's validation shape, with `page` and `redirect` added:

```json
{
  "message": "Your sign in timed out. Please start again.",
  "errors": { "email": ["Your sign in timed out. Please start again."] },
  "page": "login",
  "redirect": "https://example.com/login"
}
```

Swap any response with `Keyring::respondWith`, passing a class name or a closure:

```php
use App\Http\Responses\WelcomeBack;
use Keyring\Contracts\Responses\AuthenticatedResponse;

Keyring::respondWith(AuthenticatedResponse::class, WelcomeBack::class);
```

Your class must implement the contract. Keyring builds it through the container, passing what it knows by constructor name.

A contract that takes arguments lists them in a `BUILT_WITH` constant: `status`, `data` and `redirect` for `StatusResponse`, `reason` for `SignedOutResponse`, and `justNow` for `VerifiedResponse`. A required parameter Keyring can't fill makes `respondWith` throw at boot.

Responses of a verification also get the pipeline's `context`. For a redirect that respects the intended URL, use `Url::redirectToIntended($request, $default)` rather than Laravel's `redirect()->intended()`, which can send users to another site. `Url::intended()` reads the URL without forgetting it, and `Url::pullIntended()` reads and forgets it. Both return `null` without a session.

Build a response from a route of your own with `Keyring::response`:

```php
return Keyring::response(StatusResponse::class, status: 'device-revoked', redirect: route('login'));
```

### Status Responses

Every action that isn't a sign-in or confirmation answers through `StatusResponse`, built from `status` (a slug such as `password-updated`), `data` (extra data such as a new authenticator, often empty) and `redirect` (where to go instead, or `null`). JSON clients get the slug, its translated message, the redirect and the data:

```json
{
  "status": "authenticator-updated",
  "message": "Sign-in method updated.",
  "authenticator": { "factor": "totp", "id": "01JC4...", "name": "Work phone" }
}
```

Other requests are redirected, with the slug flashed as `status`. The flashed data is encrypted with `APP_KEY`, since it can hold a secret being set up or new recovery codes. Read it with `Keyring::result()`, or one key with `Keyring::result('recoveryCodes')`. It's `null` when nothing was flashed.

Two statuses carry where the user was headed when Keyring sent them away, to [add a sign-in method](https://keyringauth.com/docs/0.x/policies#carrying-on-afterwards) or [choose a new password](https://keyringauth.com/docs/0.x/protected-changes#carrying-on-afterwards). `authenticator-added` carries it as `continue` in its data, so a page showing new recovery codes stays up until they're saved. `password-updated` uses it as `redirect`, but only when the user was held for a new password.

```json
{
  "status": "authenticator-added",
  "message": "Sign-in method added.",
  "authenticator": { "factor": "totp", "id": "01JC4...", "name": "Authenticator app" },
  "recoveryCodes": ["..."],
  "continue": "https://example.com/invoices/42"
}
```

Messages live in `lang/en/status.php`, as `keyring::status.{slug}`. The slugs are:

`authenticator-added`, `authenticator-removed`, `authenticator-updated`, `change-password`, `code-sent`, `device-reported`, `device-revoked`, `email-change-cancelled`, `email-change-confirmed`, `email-change-invalid`, `email-change-requested`, `email-change-reverted`, `email-changed`, `email-verified`, `enroll-first`, `enrollment-started`, `impersonating`, `impersonation-ended`, `impersonation-refused`, `impersonation-started`, `not-impersonating`, `password-reset`, `password-updated`, `registered`, `registration-received`, `reset-link-sent`, `session-revoked`, `sessions-revoked`, `sign-in-to-verify`, `signed-out`, `sso-cancelled` and `verification-link-sent`.

## Pages

Keyring renders these pages:

| Name | Props |
|---|---|
| `login` | `canResetPassword`, `canRegister`, `status` (a translated message), `providers` (once `SingleSignOn` is registered: each with `name`, `label` and `url`). |
| `challenge` | See [Page Props](https://keyringauth.com/docs/0.x/sign-in-flow#page-props). Sign-ins. |
| `confirm` | As `challenge`, with `purpose: "confirm"`. Step-up. |
| `register` | None. The action expects `name`, `email`, `password` and `password_confirmation`. |
| `forgot-password`, `verify-email` | `status`. |
| `reset-password` | `token`, `email`. |
| `email-verification` | `email`, `url`, and `expires` and `signature` (posted in the body). See [Email Verification](https://keyringauth.com/docs/0.x/protected-changes#email-verification). |
| `email-change` | `action` (`confirm` or `revert`), `url`, and `token` (posted in the body). See [Protected Changes](https://keyringauth.com/docs/0.x/protected-changes#the-emailed-links). |
| `device-report` | `device`, `url`, and `expires` and `signature` (posted in the body). See [The "This Wasn't Me" Link](https://keyringauth.com/docs/0.x/devices-and-sessions#the-this-wasnt-me-link). |
| `sign-in-link` | `code`, `sameBrowser`, `url` and `expiresAt`. See [Signing In From the Email](https://keyringauth.com/docs/0.x/factors#signing-in-from-the-email). |

With Inertia, each page renders `auth/{name}`, such as `auth/login`. Without it, Keyring renders the Blade view `auth.{name}`, and Keyring doesn't ship views, so until you write one the page throws `Keyring\Exceptions\MissingPage`. Inertia only finds a missing component in the browser, unless `pages.ensure_pages_exist` in `config/inertia.php` is on.

A JSON request for a page gets its name and props instead, with the status and headers it would have had:

```json
{
  "page": "reset-password",
  "props": { "token": "...", "email": "taylor@example.com" }
}
```

For a frontend Laravel doesn't serve, set [`pages`](https://keyringauth.com/docs/0.x/configuration#pages) to `false`, and anything but JSON gets a `404`. See [Headless Frontends](https://keyringauth.com/docs/0.x/headless).

Change a page's component with `Keyring::page`, or pass a closure:

```php
Keyring::page('challenge', 'Auth/TwoFactor');

Keyring::page('login', fn (array $props) => response()->view('marketing.login', $props));
```

`challenge` and `confirm` are separate, so override `confirm` too.

## Routes

The login and registration routes are for guests only, apart from the sign-in link's page, and `/logout` requires `auth:{guard}`.

| Method | URI | Name | Purpose |
|---|---|---|---|
| `GET` | `/login` | `login` | The login page. |
| `POST` | `/login` | `login.store` | Sign in with a password. |
| `GET` | `/login/{factor}/options` | `keyring.login.options` | Passkey options, for a sign-in without a username. |
| `POST` | `/login/{factor}` | `keyring.login.factor` | Sign in with another primary factor. |
| `GET` | `/auth/{provider}/redirect` | `keyring.sso.redirect` | Sends the user to an identity provider. Registered only when `sso.providers` lists one. See [Single Sign-On](https://keyringauth.com/docs/0.x/sso). |
| `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](https://keyringauth.com/docs/0.x/sso#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 email code's [sign-in link](https://keyringauth.com/docs/0.x/factors#signing-in-from-the-email) opens, for any browser, signed in or not. `404` until `withLink()` 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. |
| `GET` | `/register` | `register` | The registration page. |
| `POST` | `/register` | `register.store` | Creates an account. |
| `POST` | `/logout` | `logout` | Signs out. |

The registration routes exist only when the `registration` feature is on. The `keyring.throttle` middleware, which uses the `keyring` rate limiter, allows six requests a minute (see [Rate Limits](https://keyringauth.com/docs/0.x/configuration#pending-logins-timebox-and-rate-limits)). The routes that spend session state take the session lock with `->block()`, so parallel requests wait their turn. `PUT /user/password` and `DELETE /user/sessions` take it too. See [Requests That Overlap a Sign In](https://keyringauth.com/docs/0.x/devices-and-sessions#requests-that-overlap-a-sign-in).

> [!NOTE]
> Your cache store must support locks.

`/login/{factor}`, its options route and the enrollment routes always `404` for a factor key that isn't registered. The verify and send routes do too, once a sign-in or step-up is under way. The challenge page's `GET` routes send an unknown key back without it.

## Events

Every event lives in `Keyring\Events`:

| Event | When | Properties |
|---|---|---|
| `Attempting` | A verification starts. | `request`, `factor` (key), `purpose` |
| `FactorChallenged` | The challenge page shows a factor. | `attempt`, `authenticator` |
| `FactorVerified` | A proof was right. | `attempt`, `authenticator`, `verification` |
| `ProviderIdentityAccepted` | An [identity provider](https://keyringauth.com/docs/0.x/sso#hearing-about-accepted-identities) account was accepted as a link. For a sign-in or confirm, it fires before the rest of the pipeline. | `user`, `authenticator`, `identity` (`Keyring\Sso\Identity`), `purpose` (`login`, `confirm` or `link`) |
| `FactorFailed` | A proof was wrong, or the user wasn't found. | `attempt` (nullable), `authenticator` (nullable), `factor`, `request` |
| `Lockout` | A rate limit refused a request. | `request`, `factor`, `retryAfter` (`null` when waiting won't help) |
| `VerificationRefused` | The final gate refused because a [mandatory step](https://keyringauth.com/docs/0.x/sign-in-flow#mandatory-steps) didn't run. | `attempt`, `factor`, `skipped` |
| `AccountLocked` | A factor is refused until a password reset, after the cap on failures or `limits.lock_after`. | `user`, `factor` |
| `Authenticated` | A login completed. | `user`, `attempt`, `device` |
| `Confirmed` | A step-up completed. | `user`, `attempt` |
| `LoggedOut` | The user signed out. | `user` |
| `SessionEnded` | Keyring ended a session itself: revoked, timed out or ended by risk. | `user`, `reason` |

Laravel's `Login`, `Logout` and `Registered` events still fire, because the guard signs users in and out. Keyring also dispatches Laravel's `Illuminate\Auth\Events\Failed` alongside `FactorFailed` (its credentials hold only the username, never a password or code), `Lockout` alongside `Lockout`, and `PasswordReset` for a reset.
