# Quick Start

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

## Introduction

This page takes a Laravel for Rust 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. Unlike the PHP package, every feature starts off, since registration, resets, password changes and email verification run code of yours. The security log is on.

## Installing

The quickest way in is the [starter kit](https://github.com/keyringauth/keyring/blob/main/rust/starter-kit/README.md): a Laravel for Rust application with Inertia, React, TypeScript and Tailwind CSS on SQLite, with a page for every page Keyring renders, settings pages for the email address, the password, sign-in methods, and sessions and devices, and a second factor required of everyone. Copy `rust/starter-kit` out and follow its README:

```bash
cp .env.example .env
cargo run -- key:generate
cargo run -- migrate
bun install
bun run build
cargo run
```

To add Keyring to an application of your own, depend on this repository, pinned to a commit:

```toml
[dependencies]
laravel-rust = { version = "=0.1.4", features = ["database-postgres"] }
laravel-keyring = { git = "https://github.com/keyringauth/keyring", rev = "<commit>", features = ["inertia"] }
```

Then add the provider, with your user provider and the actions for the features you turn on:

```rust
use laravel_keyring::{KeyringConfig, KeyringServiceProvider};

laravel::Application::configure()
    .with_providers(|providers| {
        providers.add(
            KeyringServiceProvider::<Users>::new()
                .create_users_using(CreateNewUser)
                .reset_user_passwords_using(ResetUserPassword)
                .update_user_passwords_using(UpdateUserPassword)
                .verify_emails(),
        );
    })
    .with_services(|app| {
        app.singleton(|_| async { Ok(Users) });
    })
    .with_auth(|auth, _| {
        auth.session::<Users>();
        laravel_keyring::http::verification_page::<User>(auth);
    })
    .with_config(|config, _| {
        let features = &mut config.section_mut::<KeyringConfig>().features;
        features.registration = true;
        features.reset_passwords = true;
        features.email_verification = true;
        features.update_passwords = true;
    });
```

`User` and `Users` are your user type and provider, and the three actions are yours: see [Installation](https://keyringauth.com/docs/0.x/rust/installation#preparing-your-user-model) and [Registration](https://keyringauth.com/docs/0.x/rust/sign-in-flow#registration). The provider brings Keyring's migrations, so run `cargo run -- migrate`.

The user type derives laravel-rust's `MustVerifyEmail`. That keeps the registration form from revealing who has an account, since a new user stays signed out until they verify their address.

> [!NOTE]
> New users can't sign in until they follow the verification link, so your app must send mail. With `MAIL_MAILER=log`, the link is written to the log.

## Your Pages

Keyring handles the requests, and you build the pages. With the `inertia` feature and laravel-rust's Inertia middleware, it renders `auth/{page}` components, and otherwise the views `auth.{page}`. For a frontend Laravel for Rust doesn't serve, see [Headless Frontends](https://keyringauth.com/docs/0.x/rust/headless). The [starter kit](https://github.com/keyringauth/keyring/blob/main/rust/starter-kit/README.md) 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.reset_passwords`. |
| `verify-email` | With `features.email_verification`, for a signed-in user who hasn't verified. Only needed if you set `registration.reveal_taken`. |
| `email-verification` | With `features.email_verification`. The verification link opens it, with one button. Only needed if you set `registration.reveal_taken`. |
| `email-change` | With `features.email_changes`. The confirm and undo links open it. |
| `device-report` | With `features.devices`. The "this wasn't me" link opens it. |
| `sign-in-link` | With `EmailCodes::as_extra_step().with_link()`. The link beside the code in the sign-in email opens it. See [Signing In From the Email](https://keyringauth.com/docs/0.x/rust/factors#signing-in-from-the-email). |

The login form posts `email`, `password` and an optional `remember` field to `/login`. Signed-in users go to `home`, which is `/dashboard` by default (`KEYRING_HOME`). Every page's props are in [Pages](https://keyringauth.com/docs/0.x/rust/sign-in-flow#pages), and they're the PHP package's.

## Your Settings Page

Users manage their sign-in methods on a settings page you build, at any URL. Keyring doesn't register one. Your handler passes in what the page shows, and the page calls Keyring's routes to make changes. `laravel_keyring::sign_in_methods(&user)` gives what such a page needs:

```rust
use laravel::auth::Authenticated;
use laravel::inertia::{self, Page, props};
use serde_json::json;

async fn security(user: Authenticated<User>) -> laravel::Result<Page> {
    let methods = laravel_keyring::sign_in_methods(&*user).await?;
    let activity: Vec<_> = laravel_keyring::security_log::activity(&*user, 15)
        .await?
        .into_iter()
        .map(|event| {
            json!({
                "type": event.event_type,
                "factor": event.factor,
                "ip": event.ip,
                "at": event.created_at.to_string(),
            })
        })
        .collect();

    Ok(inertia::render(
        "settings/security",
        props! { methods => serde_json::to_value(methods)?, activity => activity },
    ))
}
```

| Prop | Contents |
|---|---|
| `methods.authenticators` | The user's sign-in methods, with `factor`, `id`, `name`, `createdAt`, `lastUsedAt` (ISO 8601), `isDefault`, and `frozen` when the freeze holds one. Email codes add a masked `hint`; recovery codes add `remaining` and `replace`. The password has no row, so it's left out. |
| `methods.enrollable` | The factors a user may add, such as `totp` and `passkey`. Recovery codes only once the account has a factor for them to stand in for. |
| `methods.passwordToAdd` | Those that take the current password to add. |
| `methods.frozen`, `methods.hasSecondFactor` | The freeze, and whether the account has a second factor. |
| `activity` | Recent [security log](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#showing-recent-activity) entries. |

The page then uses [`/user/authenticators`](https://keyringauth.com/docs/0.x/rust/authenticators#routes), [`/user/devices`](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#routes), [`/user/sessions`](https://keyringauth.com/docs/0.x/rust/devices-and-sessions#listing-and-ending-sessions), [`PUT /user/password`](https://keyringauth.com/docs/0.x/rust/protected-changes#changing-the-password) and [`POST /user/email`](https://keyringauth.com/docs/0.x/rust/protected-changes#changing-the-email-address). The [browser package](https://keyringauth.com/docs/0.x/rust/frontend#managing-authenticators) wraps the authenticator routes. There's no devices list to pass in: the page loads `GET /user/devices` itself, as the starter kit's sessions page does.

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

```rust
use laravel_keyring::http::RequireFreshVerification;

fn web(route: &mut laravel::routing::Router) {
    route
        .middleware(RequireFreshVerification::<Users>::new())
        .group(|route| {
            route.get("/settings/security", security);
        });
}
```

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/rust/frontend#handling-step-up-in-javascript) section has the code.

## Testing

The test helpers are behind the crate's `testing` feature. Add it to your dev-dependencies only:

```toml
[dev-dependencies]
laravel-keyring = { git = "https://github.com/keyringauth/keyring", rev = "<commit>", features = ["testing"] }
```

`InteractsWithKeyring` adds `with_assurance`, `verified_with` and `with_proofs` to laravel-rust's `TestRequest`, and `testing::instant_timebox(&app)` skips the timing delay on failed checks. `KeyringConformance` checks that your setup keeps Keyring's guarantees. See [Testing](https://keyringauth.com/docs/0.x/rust/testing).

## Adding Features

Features are `bool`s in `features`, and each registers its routes only once it's on:

```rust
let features = &mut config.section_mut::<KeyringConfig>().features;
features.registration = true;
features.reset_passwords = true;
features.email_verification = true;
features.update_passwords = true;
features.manage_authenticators = true;
features.devices = true;
features.email_changes = true;
features.impersonation = true;
```

| Feature | What It Adds | Documentation |
|---|---|---|
| `registration` | `/register`, through your `CreatesNewUsers` action. Needs `email_verification` unless `registration.reveal_taken` is on. | [Registration](https://keyringauth.com/docs/0.x/rust/sign-in-flow#registration) |
| `reset_passwords` | Forgot and reset password, through your `ResetsUserPasswords` action. | [Resetting the Password](https://keyringauth.com/docs/0.x/rust/protected-changes#resetting-the-password) |
| `email_verification` | The verification routes, and the `verify-email` and `email-verification` pages. Needs `verify_emails()` on the provider. | [Email Verification](https://keyringauth.com/docs/0.x/rust/protected-changes#email-verification) |
| `update_passwords` | `PUT /user/password`, through your `UpdatesUserPasswords` action. The password becomes protected. | [Changing the Password](https://keyringauth.com/docs/0.x/rust/protected-changes#changing-the-password) |
| `manage_authenticators` | Adding, renaming and removing sign-in methods. Required for users to set any up. | [Managing Authenticators](https://keyringauth.com/docs/0.x/rust/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/rust/devices-and-sessions) |
| `email_changes` | Email changes, confirmed from the new address, through your `ChangesEmails` action. The address becomes protected. | [Protected Changes](https://keyringauth.com/docs/0.x/rust/protected-changes#changing-the-email-address) |
| `sso` | Signing in with identity providers in `sso.providers`. | [Single Sign-On](https://keyringauth.com/docs/0.x/rust/sso) |
| `impersonation` | `POST /impersonate/{user}` and `POST` or `DELETE /impersonate`. Nobody may impersonate until you give the provider `allow_impersonation_when()`. | [Impersonation](https://keyringauth.com/docs/0.x/rust/impersonation) |

The security log isn't a feature: it's `security_log.enabled`, on by default. A few settings live outside the list:

- **[Security emails](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#security-emails)**: sent from the start, through laravel-rust's notifications, so run a queue worker or use the `sync` queue. `notifications.turn_off(kind)` turns one off.
- **[Risk signals](https://keyringauth.com/docs/0.x/rust/risk)**: listed in `risk.signals`, which starts empty. When you turn on devices, add `NewDevice` and `InactiveAccount`.
- **[Support contact](https://keyringauth.com/docs/0.x/rust/security-log-and-emails#a-support-contact)**: `support_contact` sets who the security emails tell users to contact.
- **[Second factor requirement](https://keyringauth.com/docs/0.x/rust/policies#requiring-a-second-factor)**: the `RequireEnrollment` middleware, with `enrollment_url` set to your page for adding one.

## Adding Sign-In Methods

The password, authenticator apps, recovery codes and passkeys are on by default. The PHP package's `Keyring::factors()` with nothing listed has the password alone. Security keys and email codes are opt in:

```rust
use laravel_keyring::config::{EmailCodes, KeyProfile};
use laravel_keyring::{KeyringConfig, Requirement};

let keyring = config.section_mut::<KeyringConfig>();
keyring.webauthn.security_keys = Some(KeyProfile::security_keys());
keyring.email_codes = Some(EmailCodes::as_extra_step());
keyring.policy = Requirement::aal2().if_enrolled().no_downgrade(&[]);
```

Set a factor in `factors` to `None` or `false` to leave it out. See [Registering Factors](https://keyringauth.com/docs/0.x/rust/factors#registering-factors).

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/rust/policies#assurance-levels).

`if_enrolled()` asks for a second factor once a user has one, and is the default policy. `no_downgrade()` 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.manage_authenticators`.
2. Build the `challenge` and `confirm` pages, and the part of [your settings page](https://keyringauth.com/docs/0.x/rust/quick-start#your-settings-page) that adds and removes methods.
3. To require a second factor for everyone, append `RequireEnrollment` to the `web` group and set `enrollment_url`. See [Requiring a Second Factor](https://keyringauth.com/docs/0.x/rust/policies#requiring-a-second-factor).

For Google, Microsoft, GitHub or another identity provider, turn on `features.sso` and list them in `sso.providers`. See [Single Sign-On](https://keyringauth.com/docs/0.x/rust/sso).

## What Keyring Does Without Being Asked

These protections are on by default, as in the PHP package:

| 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, `unlock()`, or removing and re-adding the second factor. | `limits` in [Configuration](https://keyringauth.com/docs/0.x/rust/configuration#pending-logins-timebox-and-rate-limits) |
| Refused checks take at least 500ms | 500ms | `timebox` in [Configuration](https://keyringauth.com/docs/0.x/rust/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/rust/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. Your actions call `PasswordRules`. | [Password Rules](https://keyringauth.com/docs/0.x/rust/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/rust/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. | `sessions.levels` |
| Browsers clear cache and storage on sign out | Enabled | `responses.respond_with()` for [`KeyringResponse::Logout`](https://keyringauth.com/docs/0.x/rust/sign-in-flow#responses) |
| Step-up middleware | `RequireAssurance` and `RequireFreshVerification` | [Step-Up](https://keyringauth.com/docs/0.x/rust/step-up) |
