# Extending Keyring

Source: https://keyringauth.com/docs/0.x/extending

## Introduction

Once you've run `keyring:install` and a migration, Keyring works. Most of what it does is yours to change, through options, hooks and the code your app owns. `keyring:install` publishes that code into your app: the config, the migrations, a service provider, and the [actions](https://keyringauth.com/docs/0.x/protected-changes). The rest stays in the package, notifications included, where it keeps getting fixes.

Start with the table below. The [Recipes](https://keyringauth.com/docs/0.x/recipes) page has worked examples of the most common changes.

## What You Can Change

| To change | Use | See |
|---|---|---|
| Which features are on | The `features` list | [Adding Features](https://keyringauth.com/docs/0.x/quick-start#adding-features) |
| Any number, lifetime or limit | `config/keyring.php` | [Configuration](https://keyringauth.com/docs/0.x/configuration) |
| How users sign in | `Keyring::factors()`, `Keyring::extend()`, your own `Factor` | [Factors](https://keyringauth.com/docs/0.x/factors) |
| What they must prove | `Keyring::require()` | [Policies](https://keyringauth.com/docs/0.x/policies) |
| The steps a verification runs | `Keyring::pipeline()` | [The Pipeline](https://keyringauth.com/docs/0.x/sign-in-flow#the-verification-pipeline) |
| Signing in with Google, Microsoft, GitHub or OpenID Connect | The `SingleSignOn` factor and `sso.providers` | [Single Sign-On](https://keyringauth.com/docs/0.x/sso) |
| An identity provider Keyring has no driver for, or a change to one it has | `Keyring::sso()->extend()`, your own `IdentityProvider` | [Custom Drivers](https://keyringauth.com/docs/0.x/sso#custom-drivers) |
| Signing in from a route of your own, such as a provider's callback | `Keyring::attempt()` and a factor that can start a login | [Starting a Sign In Yourself](https://keyringauth.com/docs/0.x/sign-in-flow#starting-a-sign-in-yourself) |
| How a user is found, and how usernames are normalised | `Keyring::findUsersUsing()`, `Keyring::normalizeUsernamesUsing()` | [Finding the User](https://keyringauth.com/docs/0.x/sign-in-flow#finding-the-user) |
| The attribute users sign in with, and the one holding their address | `username` and `email` | [Guard and Users](https://keyringauth.com/docs/0.x/configuration#guard-and-users) |
| Creating users, resetting and changing passwords, validating a new address | The published actions in `app/Actions/Keyring` | [Protected Changes](https://keyringauth.com/docs/0.x/protected-changes) |
| Every email: wording, template, channel, or whether it's sent | `Keyring::notifications()`, your own class for a type or `null`, and `SecurityNotice::toMailUsing()` | [Security Emails](https://keyringauth.com/docs/0.x/security-log-and-emails#security-emails) |
| What a page renders | `Keyring::page()` | [Pages](https://keyringauth.com/docs/0.x/sign-in-flow#pages) |
| What Keyring answers with | `Keyring::respondWith()` and the contracts in `Keyring\Contracts\Responses` | [Responses](https://keyringauth.com/docs/0.x/sign-in-flow#responses) |
| Validation and status messages | The `keyring-lang` translation files | [Messages and Translations](https://keyringauth.com/docs/0.x/configuration#messages-and-translations) |
| The route prefix, domain and middleware | `prefix`, `domain` and `middleware` | [Routes](https://keyringauth.com/docs/0.x/configuration#routes) |
| The middleware on account changes | `changes_middleware` | [Account Changes and Enrollment](https://keyringauth.com/docs/0.x/configuration#account-changes-and-enrollment) |
| Starting an impersonation: what it takes, how long it lasts, whether the user sees it | `impersonation.*` | [Impersonation](https://keyringauth.com/docs/0.x/configuration#impersonation) |
| The form rate limits | The `keyring`, `keyring-session-changes`, `keyring-pages` and `keyring-login-options` rate limiters | [Rate Limits](https://keyringauth.com/docs/0.x/configuration#pending-logins-timebox-and-rate-limits) |
| Who may sign in at all | `Keyring::allowSignInWhen()` | [Who May Sign In](https://keyringauth.com/docs/0.x/sign-in-flow#who-may-sign-in) |
| Who may add a sign-in method | `Keyring::allowEnrollmentWhen()` | [Who May Enroll](https://keyringauth.com/docs/0.x/authenticators#who-may-enroll) |
| Who may impersonate whom | `Keyring::allowImpersonationWhen()` | [Who May Impersonate Whom](https://keyringauth.com/docs/0.x/impersonation#who-may-impersonate-whom) |
| Whether registration says when an address is taken | `registration.reveal_taken` | [Registration](https://keyringauth.com/docs/0.x/sign-in-flow#registration) |
| Whether registering signs the user in, with `registration.reveal_taken` on | `Keyring::signInAfterRegistering()` | [Saying When an Address Is Taken](https://keyringauth.com/docs/0.x/sign-in-flow#saying-when-an-address-is-taken) |
| Risk signals and what they do | `Keyring::risk()`, your own `Signal` | [Risk](https://keyringauth.com/docs/0.x/risk) |
| Where a request is located | `devices.locator`, your own `LocatesIps` | [Devices & Sessions](https://keyringauth.com/docs/0.x/devices-and-sessions) |
| Whose key attestation is trusted | `webauthn.attestation_roots`, your own `TrustsAuthenticators` | [Passkeys & Security Keys](https://keyringauth.com/docs/0.x/passkeys#trusting-each-model-separately) |
| How a browser is described | `Keyring::describeDevicesUsing()` | [Devices & Sessions](https://keyringauth.com/docs/0.x/devices-and-sessions) |
| Where sessions are registered | `sessions.driver`, your own `SessionRegistry` | [The Session Registry](https://keyringauth.com/docs/0.x/devices-and-sessions#the-session-registry) |
| Whether Keyring checks sessions on the `web` group | `sessions.middleware` | [The Session Middleware](https://keyringauth.com/docs/0.x/devices-and-sessions#the-session-middleware) |
| Whether a request sent with a replaced session ID can save it | `sessions.overlapping_requests`, your own subclass of `Keyring\Http\Middleware\StartSession` or the `SkipsReplacedSessions` trait | [Requests That Overlap a Sign In](https://keyringauth.com/docs/0.x/devices-and-sessions#requests-that-overlap-a-sign-in) |
| What's stored as an IP address | `Keyring::recordIpsUsing()` | [What's Stored](https://keyringauth.com/docs/0.x/security-log-and-emails#whats-stored) |
| Where emailed links start | `Keyring::linkRootUsing()` | [Emailed Links](https://keyringauth.com/docs/0.x/security#emailed-links) |
| The models | `Keyring::useAuthenticatorModel()` and the other four | [The Keyring Facade](https://keyringauth.com/docs/0.x/configuration#the-keyring-facade) |
| Which attributes are protected | `protected`, `Keyring::withoutProtection()` | [Protected Changes](https://keyringauth.com/docs/0.x/protected-changes) |

Devices, email changes and every sign-in method except the password are off until you turn them on. The [risk signals](https://keyringauth.com/docs/0.x/risk) come from the list in your `KeyringServiceProvider`. The provider that `keyring:install` publishes starts with a set, and an app without that provider has none. The [security notices](https://keyringauth.com/docs/0.x/security-log-and-emails#security-emails) are Keyring's own, and are sent with or without that provider.

## Replacing a Controller or Service

Keyring's controllers and services are resolved from the container, so you can swap one out. Extend Keyring's class, bind yours in the `register()` method of a service provider, and override whatever you need:

```php
use App\Http\Controllers\AuthenticatorController;
use Keyring\Http\Controllers\AuthenticatorController as KeyringAuthenticatorController;

$this->app->bind(KeyringAuthenticatorController::class, AuthenticatorController::class);
```

The services work the same way. They include `Keyring\Login\SignIn`, `Keyring\Login\StepUp`, `Keyring\Login\Detours`, `Keyring\Changes\AuthenticatorChanges`, `EmailChanges`, `PasswordChanges`, `Keyring\Devices\DeviceManager`, `Keyring\Support\Throttle` and `Keyring\WebAuthn\Ceremonies`. Their methods are public or protected, never private.

`Detours` keeps the page a user was going to when Keyring sent them to enroll or to choose a new password, so they can [carry on to it afterwards](https://keyringauth.com/docs/0.x/policies#carrying-on-afterwards). Every page it saves goes through `remember()`, which calls `put()` with the request, the detour's key (`Detours::ENROLLMENT` or `Detours::PASSWORD_CHANGE`) and the URL. Override `put()` to skip pages you never want a user carried on to. Check `$url`, not the request: on the confirm page the request is the confirm page, and `$url` is the page being confirmed. For example, an OpenID provider that answers a `prompt=none` request with an error has nothing to return to:

```php
namespace App\Login;

use Illuminate\Http\Request;
use Illuminate\Support\Uri;
use Keyring\Login\Detours as KeyringDetours;

class Detours extends KeyringDetours
{
    protected function put(Request $request, string $key, string $url): void
    {
        if (Uri::of($url)->query()->get('prompt') === 'none') {
            return;
        }

        parent::put($request, $key, $url);
    }
}
```

Bind it with `$this->app->bind(KeyringDetours::class, Detours::class)`. A page you skip leaves what was saved before alone. While `put()` runs, the requirement that sent the user to enroll is in `$this->requiring`, and the parent saves it with the page. So call the parent rather than writing to the session yourself.

Treat this as a last resort. A class you've replaced stops receiving Keyring's fixes for whatever you override. Prefer an option or hook from the table when one does the job, and call the parent's method for everything you don't change.

## Changing the Routes

The `prefix`, `domain` and `middleware` options cover most changes. To register the routes inside a group of your own, set `routes` to `false`, and call `Keyring::routes()` inside that group. Your group then sets the prefix and domain, and Keyring still adds the `middleware` option. To change a route itself, copy `vendor/keyring/keyring/routes/keyring.php` into your app and load the copy. Keep the route names: Keyring's controllers, responses and emailed links find routes by name. See [Routes](https://keyringauth.com/docs/0.x/configuration#routes).

## What Stays Fixed

A few things have no switch, because turning them off would quietly remove a protection:

- Email codes can't be registered with plain `EmailCode::class`. Keyring refuses it. Register `EmailCode::asExtraStep()`, whose name says what you're accepting. See [What Turning Email Codes On Means](https://keyringauth.com/docs/0.x/factors#what-turning-email-codes-on-means).
- A user can't remove their last way to sign in. Removing the last second factor also needs the password, typed again, and that password must be long enough to stand alone.
- An email change is confirmed from the new address and announced to the old one. The old address can undo it.
- Trusting a device takes a real second factor. A confirm page opened without a step-up behind it never accepts recovery codes.
- You can't drop the steps that check rate limits, the policy and risk from the pipeline by accident. `dangerouslyReplace()` exists for when you mean it.
- Emailed links are never built from the request's `Host` header.

Keyring also needs Eloquent user models that use the `HasKeyring` trait, and a session guard. It doesn't sign users in with token guards.

The form field names (`remember`, `trust`, `code`, `credential` and `authenticator`), the route names and the status slugs are fixed too. The [browser package](https://keyringauth.com/docs/0.x/frontend) and your pages rely on them.
