Installation
On this page
Introduction
This page covers adding the laravel-keyring crate to a Laravel for Rust application. The Quick Start has the short version, which starts from the starter kit.
The crate is version 0.1.0 and early. It isn't on crates.io yet, so an application depends on this repository, pinned to a commit, and its API will change before 1.0.
Requirements
- Rust 1.99 or later.
laravel-rust=0.1.4exactly, since laravel-rust makes no promises between 0.x releases.- A database driver for laravel-rust:
database-postgres,database-mysqlordatabase-sqlite. Keyring needs laravel-rust'sdatabasefeature, and laravel-rust refuses that without a driver. - A cache store with locks. For more than one server, a store every server shares (see Running on More Than One Server).
- Inertia, optional, through the crate's
inertiafeature. Without it, Keyring renders views. See Pages.
There's no sodium requirement: the crate can't verify Ed25519 keys, so it only offers ES256, and RS256 when you list it. See Signature Algorithms.
Installing Keyring
Depend on this repository, pinned to a commit, along with laravel-rust and a database driver:
[dependencies]laravel-rust = { version = "=0.1.4", features = ["database-postgres"] }laravel-keyring = { git = "https://github.com/keyringauth/keyring", rev = "<commit>", features = ["inertia"] }Leave out features = ["inertia"] if your pages aren't Inertia components.
Then add KeyringServiceProvider for your user provider, register that provider as a service, and register the session guard for it:
use laravel_keyring::{KeyringConfig, KeyringServiceProvider}; laravel::Application::configure() .with_providers(|providers| { providers.add(KeyringServiceProvider::<Users>::new()); }) .with_services(|app| { app.singleton(|_| async { Ok(Users) }); }) .with_auth(|auth, _| { auth.session::<Users>(); }) .with_config(|config, _| { let keyring = config.section_mut::<KeyringConfig>(); keyring.authenticatable_type = "App\\Models\\User".into(); keyring.session_user_type = "pgsql:users".into(); });Users is your user provider (see Preparing Your User Model). The with_config lines only need changing when the defaults don't match what a PHP application sharing the database writes. See The Two User Types.
There's no installer to run first, and no question to answer. keyring:install exists, but it only prints the with_config for the factors and features you name, since your config is Rust code:
cargo run -- keyring:install --factor=totp --factor=passkeys --feature=registration --feature=manage-authenticatorsIt takes the PHP command's --factor and --feature values. With an authenticator app, passkeys or security keys, it also prints enrollment_url and the with_middleware that requires a second factor of everyone, unless you pass --optional-second-factor. It writes nothing, asks nothing, and has no --force.
Run your application's migrate command to create Keyring's tables:
cargo run -- migrateIf you're moving from Fortify, read Upgrading From Fortify before you migrate.
What Gets Published
Nothing is published. The provider brings everything with it:
| What | Where It Comes From |
|---|---|
| Migrations | The provider registers them. They create the PHP package's tables, with the same columns: keyring_authenticators, keyring_devices, keyring_sessions, keyring_pending_changes, keyring_events, keyring_failure_counts, keyring_password_holds and keyring_sign_in_changes. |
| Settings | The KeyringConfig section, set in with_config. There's no config/keyring.php. See Configuration. |
| Routes, middleware and console commands | The provider registers them, and schedules keyring:prune. |
| Listeners | The provider listens to its own events, to write the security log and queue the security emails, ahead of your listeners. |
| Actions | Yours to write, as traits the provider takes: CreatesNewUsers, ResetsUserPasswords, UpdatesUserPasswords and ChangesEmails. See Configuration. |
| Emails | Keyring's own plain-text and HTML emails. Replace one with a closure on notifications. See Security Emails. |
Keyring's migrations need the password_reset_tokens table a new Laravel app has, for password resets. Your migrations create it: email (primary), token and created_at.
The tables' authenticatable_id columns are big integers, so user IDs must be integers.
Preparing Your User Model
There's no model and no HasKeyring trait. Your application needs a user type and a user provider for its session guard. The provider finds users by ID and by the username on the login form, and Keyring uses the same provider to find the user a typed username names, so an account's rate limits are its user's. The user implements laravel-rust's ReceivesMail, the address Keyring's security emails go to:
use laravel::auth::{Authenticatable, MustVerifyEmail, UserProvider};use laravel::db;use laravel::hash::PasswordHash; #[derive(Clone, db::FromRow, MustVerifyEmail)]pub struct User { pub id: i64, pub name: String, pub email: String, #[auth(email_verified_at)] pub verified: bool, pub password: Option<PasswordHash>, pub remember_token: Option<String>,} impl laravel::notification::ReceivesMail for User { fn mail_address(&self) -> Option<laravel::mail::Address> { Some(laravel::mail::Address::new(&self.email).with_name(&self.name)) }} impl Authenticatable for User { type Id = i64; fn auth_id(&self) -> i64 { self.id } fn auth_password(&self) -> Option<&PasswordHash> { self.password.as_ref() } fn remember_token(&self) -> Option<&str> { self.remember_token.as_deref() }} pub struct Users; impl UserProvider for Users { type User = User; async fn find(&self, id: &i64) -> laravel::Result<Option<User>> { db::query!( "SELECT id, name, email, email_verified_at IS NOT NULL AS verified, password, remember_token FROM users WHERE id = {id}" ) .select_one_as() .await } async fn find_for_login(&self, email: &str) -> laravel::Result<Option<User>> { db::query!( "SELECT id, name, email, email_verified_at IS NOT NULL AS verified, password, remember_token FROM users WHERE email = {email}" ) .select_one_as() .await } async fn update_password(&self, user: &User, password: &PasswordHash) -> laravel::Result<()> { // Only Keyring's password flows may change it. See Protected Changes. laravel_keyring::protection::guard(&["password"])?; let (id, password) = (user.id, password.as_str()); db::query!("UPDATE users SET password = {password} WHERE id = {id}").update().await?; Ok(()) } async fn update_remember_token(&self, user: &User, token: &str) -> laravel::Result<()> { let id = user.id; db::query!("UPDATE users SET remember_token = {token} WHERE id = {id}").update().await?; Ok(()) } async fn mark_email_as_verified(&self, user: &User) -> laravel::Result<()> { let (id, now) = (user.id, laravel::now().strftime("%Y-%m-%d %H:%M:%S").to_string()); db::query!("UPDATE users SET email_verified_at = {now} WHERE id = {id}").update().await?; Ok(()) }}The starter kit's users.rs is this file. What the PHP trait does, your application does where it saves and deletes users:
$user->keyringisUserKeyring::of(&user), andlaravel_keyring::sign_in_methods(&user)gives a settings page what it shows. See From PHP.- Protected attributes. laravel-rust has no model events, so call
laravel_keyring::protection::guard(&[...])with the attributes a save changes wherever you save users, asupdate_password()does above. It fails outside Keyring's flows for a protected attribute. See Protected Attributes. - Deleting a user. Call
laravel_keyring::user_soft_deleted(&user)orlaravel_keyring::user_deleted(&user)where you delete users. The first forgets their reset links and signs them out everywhere. The second also deletes their authenticators, devices, pending changes, failure counts, log entries, password holds and sign-in changes.
A user type that derives MustVerifyEmail gets no security emails until its address is verified, as in the PHP package. If your application tracks verification some other way, return None from mail_address() for an address nobody has verified yet, since it may be anyone's. A user with no address gets None too, and is sent nothing.
MustVerifyEmail and features.email_verification go together, as in the PHP package:
- With registration on and hiding taken addresses, the application won't boot unless email verification is on, with
verify_emails()on the provider.registration.reveal_takenturns that rule off. - laravel-rust asks an application whose user type derives
MustVerifyEmailto mark its verification page, which a provider can't do, so calllaravel_keyring::http::verification_page::<User>(auth)inwith_auth. See Email Verification. - With registration on, adding a sign-in method is a server error, naming what to change, for a user who can't prove their address. See Managing Authenticators.
Keyring looks users up with the provider's find_for_login(), by email by default (username changes the field the form sends). Lookups trim and lowercase the input, so store addresses the same way. laravel_keyring::normalize_username() does that, and normalize_usernames_using() on the provider changes it. See Finding the User.
The Two User Types
The PHP package writes a user's type in two places, and the crate has a setting for each:
| Setting | Column | What the PHP Package Writes | Default |
|---|---|---|---|
authenticatable_type |
keyring_authenticators.authenticatable_type, keyring_failure_counts.authenticatable_type, keyring_devices.authenticatable_type |
The user model's morph class, such as App\Models\User, or its morph map alias |
App\Models\User |
session_user_type (KEYRING_SESSION_USER_TYPE) |
keyring_sessions.user_type |
The connection and table the user's ID is unique in, as connection:table, such as pgsql:users |
DB_CONNECTION:users, or postgres:users when DB_CONNECTION is unset |
When the two share a database, set both to what the PHP side writes. Laravel names a PostgreSQL connection pgsql where laravel-rust's default is postgres, so the default session_user_type is often not what the PHP side writes: keyring:install prints the value in use. Each setting fails closed in its own way:
- A sign in with authenticators stored under any other
authenticatable_typefails with a server error that names both types, rather than signing in on the password alone. So an application supports one user type. - A sign in for a user with open sessions under another
session_user_typefor the same table (pgsql:usersagainstpostgres:users, say) fails with a server error that names both, rather than splitting their sessions in two, where each side's sessions list would hide the other's. Only sessions that have expired, or were ended, don't count: one unused for longer thansessions.idlestill does, since the PHP side's idle setting may differ. A mismatch is only found once both sides have a session for the same user, so check the setting before going live.
session_user_type has to be connection:table, both parts there: anything else, such as the user's morph class, stops the application booting, since without the table Keyring couldn't lock the user's row or find their sessions under another type.
Signing out everywhere, a password change or reset, deleting the account and signing out a device end the user's sessions under any other connection:table for the same table too, so the PHP side's are never left open. A type for another table, such as pgsql:admins, is another user who happens to share the ID, and is left alone. So two different sets of users in tables with the same name on different connections (pgsql:users and mysql:users) aren't supported: they'd be taken for one user.
When session_user_type was wrong and you've set it to what the PHP side writes, the sessions this application wrote under the old value block their users' sign ins until they expire. Move them over instead, with the two values from the error:
UPDATE keyring_sessions SET user_type = 'pgsql:users' WHERE user_type = 'postgres:users';Frontend
If you offer passkeys or security keys, install the browser package, @keyringjs/keyring. It also has helpers for the challenge page, and works with the crate unchanged, since the crate answers the same requests:
npm install @keyringjs/keyringFor an Inertia frontend, turn on the crate's inertia feature, which turns on laravel-rust's, and add laravel-rust's Inertia middleware to the web group. Keyring's pages are then the components auth/login and the rest. See Frontend.
Routes Keyring Registers
Keyring registers its routes in the web middleware group, so they get the session, cookies and CSRF check. laravel-rust's routes have no names, so there are no login or password.reset names to clash with, but don't register your own routes at Keyring's paths.
The full list is in The Sign In Flow, Step-Up, Managing Authenticators, Devices & Sessions and Protected Changes. To change the prefix or domain, or turn the routes off, see Configuration.
The provider also adds middleware to the web group: BlockSession and EndUnsavedSignIns just ahead of StartSession, and AuthenticateSession and RequirePasswordChange at the end. See The Session Middleware.
After Installing
- Set
APP_URLto the address users visit. Keyring builds emailed links and the single sign-on callback from it, and passkeys and security keys only work on that origin unless you configure others. See Passkeys & Security Keys. - Use the PHP side's
APP_KEYwhen the two share a database. Keyring encrypts pending logins and authenticators' secrets with it, and keys recovery codes, sent codes and session handles with it. - Build your pages. If you require a second factor, build the page at
enrollment_urltoo. - Run a queue worker, or use the
syncqueue connection. Security emails are queued. Sign-in codes are sent straight away. - Run your application's scheduler every minute (
schedule:run). Keyring scheduleskeyring:prunedaily atprune_at, which deletes old devices, finished email changes, old security log entries, ended sessions, old sign-in changes, and password holds lifted a year ago. See Pruning. - Sessions end after two hours without activity unless the browser ticked "remember me". To change that, set
sessions.idle. See Timeouts. - Keep signed-in routes in the
webgroup, whereAuthenticateSessionruns. Otherwise, a revoked or timed-out session keeps working on them. See The Session Middleware. - To hear about every session that ends, set
sessions.sweep_every. Keyring then scheduleskeyring:sweep. See Sweeping Ended Sessions. keyring:sign-outsigns one user out everywhere, and--allsigns everyone out. See For Administrators.- Behind a load balancer or proxy, list it with laravel-rust's
trust_proxies. See Trusted Proxies.