Getting StartedQuick Start

Quick Start

On this page

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: 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:

Terminal
cp .env.example .envcargo run -- key:generatecargo run -- migratebun installbun run buildcargo 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 and 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. The starter kit 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.

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, 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 entries.

The page then uses /user/authenticators, /user/devices, /user/sessions, PUT /user/password and POST /user/email. The browser package 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, 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 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.

Adding Features

Features are bools 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
reset_passwords Forgot and reset password, through your ResetsUserPasswords action. Resetting the Password
email_verification The verification routes, and the verify-email and email-verification pages. Needs verify_emails() on the provider. Email Verification
update_passwords PUT /user/password, through your UpdatesUserPasswords action. The password becomes protected. Changing the Password
manage_authenticators Adding, renaming and removing sign-in methods. Required for users to set any up. Managing Authenticators
devices A device cookie, "trust this device", the list of signed-in devices, and "this wasn't me" links. Devices & Sessions
email_changes Email changes, confirmed from the new address, through your ChangesEmails action. The address becomes protected. Protected Changes
sso Signing in with identity providers in sso.providers. Single Sign-On
impersonation POST /impersonate/{user} and POST or DELETE /impersonate. Nobody may impersonate until you give the provider allow_impersonation_when(). 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: 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: listed in risk.signals, which starts empty. When you turn on devices, add NewDevice and InactiveAccount.
  • Support contact: support_contact sets who the security emails tell users to contact.
  • Second factor requirement: 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.

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.

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

For Google, Microsoft, GitHub or another identity provider, turn on features.sso and list them in sso.providers. See Single Sign-On.

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
Refused checks take at least 500ms 500ms timebox in Configuration
Registration answers the same for taken and free addresses Enabled registration.reveal_taken
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
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
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
Step-up middleware RequireAssurance and RequireFreshVerification Step-Up