# Quick Start

Source: https://keyringauth.com/docs/0.x/quick-start

## Introduction

This page takes a new Laravel application to a working sign-in: the install, the pages to build, your settings page, and the features and sign-in methods to add next.

Signing in with a password, signing out, challenges and step-up are always on. A default install adds registration, password resets, email verification, password changes and the security log.

## Installing

Install the package, then run the installer and your migrations:

```bash
composer require keyring/keyring

php artisan keyring:install

php artisan migrate
```

The installer asks which sign-in methods to add besides the password, whether everyone must set up a second factor, and which features to turn on. With `--no-interaction`, you get the defaults. Everything else is published, so you can turn it on later by uncommenting a line.

Add the `HasKeyring` trait to your `User` model, and implement `MustVerifyEmail`:

```php
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Keyring\Concerns\HasKeyring;

class User extends Authenticatable implements MustVerifyEmail
{
    use HasKeyring;
}
```

The interface keeps the registration form from revealing who has an account, since a new user stays signed out until they verify their address. Without the trait, signing in throws `Keyring\Exceptions\MissingTrait`.

> [!NOTE]
> New users can't sign in until they follow the verification link, so your app must send mail. In a new Laravel application, the default `log` mailer writes the link to `storage/logs/laravel.log`.

## Your Pages

Keyring handles the requests, and you build the pages. With Inertia it renders `auth/{page}` components, and without Inertia, the Blade views `auth.{page}`. For a frontend Laravel doesn't serve, see [Headless Frontends](https://keyringauth.com/docs/0.x/headless), and the [example application](https://github.com/keyringauth/example) has every page in React. Build the pages for the features you turn on:

| Page | When It's Needed |
|---|---|
| `login` | Always. |
| `challenge` | When you add a second sign-in method. It asks for the next factor. |
| `confirm` | For step-up, which changing the password and adding sign-in methods use. It may render the same component as `challenge`. |
| `register` | With `Features::registration()`. Posts `name`, `email`, `password` and `password_confirmation` to `/register`. |
| `forgot-password`, `reset-password` | With `Features::resetPasswords()`. |
| `verify-email` | With `Features::emailVerification()`, for a signed-in user who hasn't verified. Only needed if you set `registration.reveal_taken`. |
| `email-verification` | With `Features::emailVerification()`. The verification link opens it, with one button. Only needed if you set `registration.reveal_taken`. |
| `email-change` | With `Features::emailChanges()`. The confirm and undo links open it. |
| `device-report` | With `Features::devices()`. The "this wasn't me" link opens it. |
| `sign-in-link` | With `EmailCode::asExtraStep()->withLink()`. The link beside the code in the sign-in email opens it. See [Signing In From the Email](https://keyringauth.com/docs/0.x/factors#signing-in-from-the-email). |

The login form posts `email`, `password` and an optional `remember` field to `/login`:

```blade
{{-- resources/views/auth/login.blade.php --}}
<form method="POST" action="{{ route('login.store') }}">
    @csrf
    <input name="email" type="email" value="{{ old('email') }}" autocomplete="username" required>
    <input name="password" type="password" autocomplete="current-password" required>
    @if ($status) <p>{{ $status }}</p> @endif
    @error('email') <p>{{ $message }}</p> @enderror
    <button>Sign in</button>
</form>
```

Signed-in users go to `home` in `config/keyring.php`, which is `/dashboard` by default. A new Laravel application has no such route, so add one or change `home`. Every page's props are in [Pages](https://keyringauth.com/docs/0.x/sign-in-flow#pages).

## Your Settings Page

Users manage their sign-in methods on a settings page you build, at any URL. Keyring doesn't register one. Your controller passes in what the page shows, and the page calls Keyring's routes to make changes:

```php
use Illuminate\Http\Request;
use Inertia\Inertia;
use Keyring\Contracts\Enrollable;
use Keyring\Contracts\Factor;
use Keyring\Devices\DeviceManager;
use Keyring\Facades\Keyring;
use Keyring\Models\Authenticator;

class SecurityController
{
    public function edit(Request $request, DeviceManager $devices)
    {
        $user = $request->user();

        return Inertia::render('settings/security', [
            'authenticators' => $user->keyring->all()
                ->reject(fn (Authenticator $authenticator) => $authenticator->isVirtual())
                ->map(fn (Authenticator $authenticator) => [
                    ...$authenticator->factor()->present($authenticator),
                    'isDefault' => $authenticator->is_default,
                ])
                ->values(),
            'enrollable' => Keyring::registered()
                ->filter(fn (Factor $factor) => $factor instanceof Enrollable)
                ->keys(),
            'devices' => $devices->list($request, $user),
            'activity' => Keyring::activity($user, 15)->map(fn ($event) => [
                'type' => $event->type,
                'factor' => $event->factor,
                'ip' => $event->ip,
                'at' => $event->created_at->toIso8601String(),
            ]),
        ]);
    }
}
```

| Prop | Contents |
|---|---|
| `authenticators` | The user's sign-in methods, with `factor`, `id`, `name`, `createdAt`, `lastUsedAt` (ISO 8601) and `isDefault`. Email codes add a masked `hint`; recovery codes add `remaining` and `replace`. The password has no row, so it's left out. |
| `enrollable` | The factors a user may add, such as `totp` and `passkey`. Label `recovery` "generate recovery codes", since it only works once a second factor exists. `sso` appears when [single sign-on](https://keyringauth.com/docs/0.x/sso#linking-and-unlinking) is registered. |
| `devices` | Where the user is signed in, with `Features::devices()` on. The same list as [`GET /user/devices`](https://keyringauth.com/docs/0.x/devices-and-sessions#listing-and-revoking-devices). |
| `activity` | Recent [security log](https://keyringauth.com/docs/0.x/security-log-and-emails#showing-recent-activity) entries, with `Features::securityLog()` on. |

The page then uses [`/user/authenticators`](https://keyringauth.com/docs/0.x/authenticators#routes), [`/user/devices`](https://keyringauth.com/docs/0.x/devices-and-sessions#routes), [`/user/sessions`](https://keyringauth.com/docs/0.x/devices-and-sessions#listing-and-ending-sessions), [`PUT /user/password`](https://keyringauth.com/docs/0.x/protected-changes#changing-the-password) and [`POST /user/email`](https://keyringauth.com/docs/0.x/protected-changes#changing-the-email-address). The [browser package](https://keyringauth.com/docs/0.x/frontend#managing-authenticators) wraps the authenticator routes.

Routes that change something need a [fresh verification](https://keyringauth.com/docs/0.x/step-up#fresh-verification), which lasts 15 minutes by default. Listing doesn't. Add `keyring.fresh` to the page's middleware, so users confirm once when it opens:

```php
Route::get('/settings/security', [SecurityController::class, 'edit'])
    ->middleware(['auth', 'verified', 'keyring.fresh:15m']);
```

Signing in counts as a verification. If the page stays open longer, the next JSON request gets a `423` response with a `redirect` to the confirm page. Send the browser there. Once the user confirms, Keyring returns them to the page to try again. The [Handling Step-Up in JavaScript](https://keyringauth.com/docs/0.x/frontend#handling-step-up-in-javascript) section has the code.

## Testing

The `InteractsWithKeyring` trait adds helpers to your base test case: `withAssurance`, `verifiedWith`, `freshAt`, `totpCode` and `sessionErrors`. It also skips the timing delay on failed checks:

```php
use Keyring\Testing\InteractsWithKeyring;

abstract class TestCase extends BaseTestCase
{
    use InteractsWithKeyring;
}
```

Add `KeyringConformance` to a test class to check that your setup keeps Keyring's guarantees. See [Testing](https://keyringauth.com/docs/0.x/testing).

## Adding Features

Features are turned on in `config/keyring.php`, and each one registers its routes only once it's in the list. The installer writes this list:

```php
use Keyring\Features;

'features' => [
    Features::registration(),
    Features::resetPasswords(),
    Features::emailVerification(),
    Features::updatePasswords(),
    // Features::manageAuthenticators(),
    // Features::devices(),
    // Features::emailChanges(),
    Features::securityLog(),
    // Features::impersonation(),
],
```

| Feature | What It Adds | Documentation |
|---|---|---|
| `registration()` | `/register`, through your `CreateNewUser` action. Needs `emailVerification()` unless `registration.reveal_taken` is on. | [Registration](https://keyringauth.com/docs/0.x/sign-in-flow#registration) |
| `resetPasswords()` | Forgot and reset password, through your `ResetUserPassword` action. | [Resetting the Password](https://keyringauth.com/docs/0.x/protected-changes#resetting-the-password) |
| `emailVerification()` | Laravel's verification routes, and the `verify-email` and `email-verification` pages. | [Email Verification](https://keyringauth.com/docs/0.x/protected-changes#email-verification) |
| `updatePasswords()` | `PUT /user/password`. Changing the password anywhere else throws. | [Changing the Password](https://keyringauth.com/docs/0.x/protected-changes#changing-the-password) |
| `manageAuthenticators()` | Adding, renaming and removing sign-in methods. Required for users to set any up. | [Managing Authenticators](https://keyringauth.com/docs/0.x/authenticators) |
| `devices()` | A device cookie, "trust this device", the list of signed-in devices, and "this wasn't me" links. | [Devices & Sessions](https://keyringauth.com/docs/0.x/devices-and-sessions) |
| `emailChanges()` | Email changes, confirmed from the new address. Changing the email anywhere else throws. | [Protected Changes](https://keyringauth.com/docs/0.x/protected-changes#changing-the-email-address) |
| `securityLog()` | The `keyring_events` table and "was this you?" alerts. On by default. | [Security Log & Emails](https://keyringauth.com/docs/0.x/security-log-and-emails) |
| `impersonation()` | `POST /impersonate/{user}` and `POST` or `DELETE /impersonate`. Nobody may impersonate until you call `Keyring::allowImpersonationWhen()`. | [Impersonation](https://keyringauth.com/docs/0.x/impersonation) |

A few settings live outside the list:

- **[Security emails](https://keyringauth.com/docs/0.x/security-log-and-emails#security-emails)**: sent from the start. Use `Keyring::notifications([...])` in `KeyringServiceProvider` to replace one or turn it off.
- **[Risk signals](https://keyringauth.com/docs/0.x/risk)**: listed in `Keyring::risk()->signals([...])` in `KeyringServiceProvider`. When you turn on devices, uncomment `NewDevice` and `InactiveAccount`.
- **[Support contact](https://keyringauth.com/docs/0.x/security-log-and-emails#a-support-contact)**: `support_contact` in `config/keyring.php` sets who the security emails tell users to contact.
- **[Second factor requirement](https://keyringauth.com/docs/0.x/policies#requiring-a-second-factor)**: the `keyring.enrolled` middleware, with `enrollment_url` set to your page for adding one.

## Adding Sign-In Methods

Sign-in methods are listed in `app/Providers/KeyringServiceProvider.php`. The ones you didn't pick at install are commented out. Uncomment the ones you want, along with recovery codes:

```php
use Keyring\Facades\Keyring;
use Keyring\Factors;
use Keyring\Login\Requirement;

Keyring::factors([
    Factors\Password::class,
    Factors\Totp::class,
    Factors\RecoveryCodes::class,
    Factors\WebAuthn::passkeys(),
    // Factors\WebAuthn::securityKeys(),
    // Factors\EmailCode::asExtraStep(),
]);

Keyring::require(Requirement::aal2()->ifEnrolled()->noDowngrade());
```

AAL is NIST's authenticator assurance level, a scale for how strongly a session was proved. A password alone is AAL1. A password plus an authenticator app, or a passkey on its own, reaches AAL2. See [Assurance Levels](https://keyringauth.com/docs/0.x/policies#assurance-levels).

`ifEnrolled()` asks for a second factor once a user has one. `noDowngrade()` stops a user with an established passkey, one held for 7 days by default, from being talked into something weaker.

To finish:

1. Turn on `Features::manageAuthenticators()`.
2. Build the `challenge` and `confirm` pages, and the part of [your settings page](https://keyringauth.com/docs/0.x/quick-start#your-settings-page) that adds and removes methods.
3. To require a second factor for everyone, uncomment the `keyring.enrolled` line in `KeyringServiceProvider` and set `enrollment_url` in `config/keyring.php`. See [Requiring a Second Factor](https://keyringauth.com/docs/0.x/policies#requiring-a-second-factor).

For Google, Microsoft, GitHub or another identity provider, add `Factors\SingleSignOn::class`. See [Single Sign-On](https://keyringauth.com/docs/0.x/sso).

## What Keyring Does Without Being Asked

These protections are on by default:

| Protection | Default | How to Change It |
|---|---|---|
| Sign-in rate limits | 5 a minute per account, 20 per IP address. After 100 failures in a row, a method is refused until a password reset, `Keyring::unlock()`, or removing and re-adding the second factor. | `limits` in [Configuration](https://keyringauth.com/docs/0.x/configuration#pending-logins-timebox-and-rate-limits) |
| Refused checks take at least 500ms | 500ms | `timebox` in [Configuration](https://keyringauth.com/docs/0.x/configuration#pending-logins-timebox-and-rate-limits) |
| Registration answers the same for taken and free addresses | Enabled | [`registration.reveal_taken`](https://keyringauth.com/docs/0.x/sign-in-flow#registration) |
| Password rules | 15 characters without a second factor, 8 with one. Common passwords, and ones built from the user's name or email or your app's name, are refused. Breached passwords are refused in production. | [Password Rules](https://keyringauth.com/docs/0.x/protected-changes#password-rules) |
| Sessions are recorded with IP address and browser | Sessions end after 2 hours idle, or 30 days after sign-in. "Remember me" returns a browser for up to 14 days away. | `sessions` in [Configuration](https://keyringauth.com/docs/0.x/configuration#sessions) |
| Assurance levels lapse, as NIST recommends | AAL2 lapses after 1 hour idle or 24 hours. AAL3 lapses after 15 minutes idle or 12 hours. The session stays signed in at a lower level unless `sessions.end_on_lapse` is on. | `sessions.levels` |
| Browsers clear cache and storage on sign out | Enabled | A custom [`LogoutResponse`](https://keyringauth.com/docs/0.x/sign-in-flow#responses) |
| Step-up middleware | `keyring:aal2` and `keyring.fresh:15m` | [Step-Up](https://keyringauth.com/docs/0.x/step-up) |
