The Sign In Flow
On this page
- Introduction
- Signing In With a Password
- Finding the User
- Who May Sign In
- Signing In With a Passkey
- Starting a Sign In Yourself
- The Challenge Page
- Page Props
- Choosing an Authenticator
- Verifying
- Sending Codes
- Finishing the Login
- Where They Go Next
- Registration
- Without Revealing Who Has an Account
- Saying When an Address Is Taken
- Signing Out
- The Verification Pipeline
- Customising the Steps
- Mandatory Steps
- Writing a Step
- Responses
- Status Responses
- Pages
- Routes
- Events
Introduction
Signing in works as in the PHP package, with the same routes, JSON and status codes, held to it by the contract suite. The user proves a first factor, usually their password, by posting to /login. Keyring then asks the policy what else they need. If nothing, they're signed in. Otherwise Keyring saves a pending attempt in the session, as JSON encrypted with the application key, and sends them to the challenge page, repeating until the requirement is met.
A pending attempt lasts pending_logins, 10 minutes by default. It ends early if the user is gone, their password changes, their address changes (read through your ChangesEmails action, or email_for_verification() for a user type that derives MustVerifyEmail), or an authenticator it proved is taken off the account. A user type with neither has no address Keyring can read, so only a new password ends its pending logins. Step-up uses the same challenge page and pipeline, with the purpose confirm.
Signing In With a Password
Post email (or your username field) and password to /login, with an optional remember for "remember me". A wrong password and an unknown account get the same error on the username field, in the same time.
Finding the User
Keyring finds the user with your provider's find_for_login(), given the value after trimming and lowercasing it. There's no Keyring::findUsersUsing(): to sign in with an email address or a username, look up both in find_for_login(). To normalise usernames your own way (for lookups, rate limits, email changes and reservations), give the provider normalize_usernames_using():
KeyringServiceProvider::<Users>::new() // Keep usernames' case. .normalize_usernames_using(|username: &str| username.trim().to_owned());laravel_keyring::normalize_username() normalises one as Keyring does.
Who May Sign In
To keep an account out, such as a banned one, tell the provider who may sign in:
KeyringServiceProvider::<Users>::new().allow_sign_in_when(|user: &User| !user.banned);For a check that has to look something up, implement laravel_keyring::AuthorizesSignIn instead. Keyring asks it wherever a session starts or carries on: every first factor, a pending login, "remember me", impersonation and each signed-in request. A refused session is signed out with every other session of the account (not_allowed, SessionsRevoked), and the account gets the same answer as one that doesn't exist. laravel_keyring::allows_sign_in(&user) asks it from your own code.
Warning
Keyring only learns an account is kept out when one of its sessions makes a request. Sign the account out when you set the flag, as OWASP ASVS 5.0.0 (7.4.2) asks:
use laravel_keyring::Sessions; ban(&user).await?; Sessions::<Users>::sign_out_everywhere(&user, None).await?;Signing In With a Passkey
A passkey signs in without a username, in two requests, as in the PHP package. GET /login/passkey/options returns WebAuthn options under options, with no allowCredentials, and keeps the challenge in the session for webauthn.login_options_for. Then POST /login/passkey takes the browser's response as credential, and optionally remember. The options are limited to limits.login_options (60) a minute from one address. The browser package's usePasskeyLogin handles both (see Frontend). Security keys can't start a sign in, so their routes return 404.
Starting a Sign In Yourself
POST /login/{factor} starts a sign in with any factor that supports it. When a proof arrives somewhere else, such as a callback from your own partner service, call sign_in::attempt() from your route, as Keyring::attempt():
use laravel::auth::Auth;use laravel::http::{Request, Response};use laravel::session::Session;use laravel_keyring::sign_in::{self, SignInWith}; async fn partner_callback(auth: Auth<User>, session: Session, request: Request) -> laravel::Result<Response> { sign_in::attempt(&auth, &session, &request, SignInWith::Factor("partner".to_owned())).await}It runs the same pipeline as the login form, and answers as that route would: signed in, on to the challenge (202), or the refusal as an error (422 on the username field, 429 for a lockout). SignInWith::Password and SignInWith::Passkey read what the request sent, as POST /login and POST /login/passkey do, and SignInWith::Sso { identity, remember } signs in whoever linked an identity provider's account (see Single Sign-On).
laravel-rust has no ->block(), so list the route in sessions.block for it to take the session lock: (Method::POST, "/partner/callback".to_owned()). A browser someone is already signed in on is sent home, where the PHP package signs the new user in over them. Keep your own routes away from /auth/{provider}/..., which single sign-on uses.
The Challenge Page
GET /login/challenge shows the next factor. GET /login/challenge/{factor} shows that factor if it brings the user closer to the requirement. Without a pending login, a JSON request gets a 422 naming the login page.
Page Props
The props are the PHP package's, as the PHP docs describe: purpose, factor, authenticator, challenge, alternatives, canTrustDevice and expiresAt (RFC 3339). For a factor of your own, challenge is what ChecksProofs::challenge() gives, or [] for a primary factor.
Choosing an Authenticator
By default the page shows the user's default authenticator, or else the first useful one by priority. Add ?authenticator={id} to the factor's URL to pick a particular one, as in the PHP package.
Verifying
Post the proof to POST /login/challenge/{factor}, with the PHP package's fields: password, code, credential, an optional authenticator, and an optional trust. A wrong proof is a 422 on the factor's field, and the sign in can go on. The guess limits, timeouts and messages are the PHP package's, in English.
Sending Codes
Code factors send a code only when asked, by posting to POST /login/challenge/{factor}/send, which answers code-sent. Viewing or prefetching the page sends nothing. It answers 404 for a factor that sends none. The limits are the PHP package's: three codes per factor every ten minutes in each of three buckets (limits.codes), and a fourth request in a bucket gets a 429 on code.
With EmailCodes::as_extra_step().with_link(), the sign-in email also carries a link. Opened in the browser that started the sign in, its page posts the code to POST /login/challenge/email-code/link, which verifies it as POST /login/challenge/email-code would. Opened anywhere else, the page asks for the code from the email to be typed where the sign in started, without showing it.
Finishing the Login
When the requirement is met, Keyring does what the PHP package does: signs the user into the guard (with "remember me" if ticked), moves the browser to a new session ID, records what they proved, recognises or registers the device and the session, dispatches Authenticated, answers the "was this you?" alerts, dispatches NewDeviceSignedIn if the device is new, and redirects to the intended URL or home. A JSON request gets 200 with {"status": "authenticated", "redirect": "...", "alerts": [...]}.
Where They Go Next
The intended URL is url.intended, usually the page a guest was stopped on. Keyring only follows it on your app's own origins (the request's and APP_URL's), as in the PHP package. Anything else is dropped, and the user goes to home. http::pull_intended(&session) reads and forgets it from your own code, with the same check.
Registration
POST /register passes the form to your CreatesNewUsers action, given to the provider with create_users_using(), with features.registration on. Its validate() checks the form and returns what create() needs. Passwords are in Unicode's NFC form before your action sees them:
use laravel::auth::UserProvider;use laravel::db;use laravel_keyring::{CreatesNewUsers, Input, PasswordRules};use serde_json::Value; struct CreateNewUser; impl CreatesNewUsers<User> for CreateNewUser { async fn validate(&self, input: Input) -> laravel::Result<Input> { // There's no user yet, so the name and address given count as theirs. let given = ["name", "email"].map(|field| input.get(field).and_then(Value::as_str)); PasswordRules::new().context(given.into_iter().flatten()).check(&input).await?; Ok(input) } async fn create(&self, input: Input) -> laravel::Result<User> { let email = input.get("email").and_then(Value::as_str).unwrap_or_default(); let password = input.get("password").and_then(Value::as_str).unwrap_or_default(); let hash = laravel::hash::make(password).await?; let hash = hash.as_str(); db::query!("INSERT INTO users (email, password) VALUES ({email}, {hash})").insert().await?; Users.find_for_login(email).await?.ok_or_else(|| laravel::Error::msg("the user wasn't saved")) }}The starter kit's actions.rs has a fuller one, which validates the name and address too. PasswordRules is the PHP package's password rules (see Password Rules).
Don't check whether the address is free yourself. Keyring does that after validate() and before create(): an address counts as taken when your provider's find_for_login() finds an account with it, when it's held for its previous owner during an email change, or when the insert breaks a unique index. The PHP package also counts a soft-deleted account, so if you soft-delete users, answer CreatesNewUsers::taken() yourself: Some(true) or Some(false), or None for Keyring's own check. A password bcrypt would cut short or can't take (over 72 bytes, or a NUL) is refused on password whatever your rules say.
Without Revealing Who Has an Account
By default (registration.reveal_taken is false), the form never shows whether an address has an account, as OWASP ASVS 5.0.0 (6.3.8) asks, and as the PHP docs describe. Every address gets 200 { "status": "registration-received", "message", "page": "login", "redirect" }, in at least timebox, nobody is signed in, and the emails go out after the answer: a new user's verification link, another link to an account that was never verified, or the already_registered email to a taken address.
There's no Laravel Registered event: Keyring sends the verification link itself, as its own email (see Emails a Flow Needs). Something your create() fails with other than InvalidInput is reported and answered the same.
A new user can't sign in until their address is verified, so a right password is refused as a wrong one. That gate is its own setting, registration.verified_before_sign_in, on by default, so it can match the PHP side whether or not registration is on here. Email verification must be on, with verify_emails() on the provider: registration that hides who has an account without it stops the application booting.
Saying When an Address Is Taken
config.section_mut::<KeyringConfig>().registration.reveal_taken = true;A taken address is a 422 "has already been taken" on email, beside the form's other errors, and a new user is signed in straight away, with their password counting as proved, answering as a sign in does.
Warning
This tells anyone who asks whether an address has an account, through the error and through being signed in. It doesn't meet ASVS 6.3.8.
To keep new users signed out, for example until an admin approves them, give the provider sign_in_after_registering(), with false or a closure of the user and the request. They get the registered status, naming the login page:
KeyringServiceProvider::<Users>::new() .sign_in_after_registering(|user: &User, _request: &laravel::http::Request| !user.needs_approval);Signing Out
POST /logout ends the registered session, signs the user out and moves the browser to a new session. JSON clients get 204 No Content, and everyone else is redirected to /. The response sends Clear-Site-Data: "cache", "storage" and leaves cookies alone, so the device survives.
Signing out uses laravel-rust's Auth::logout, which gives the user a new remember token, so their other remembered browsers are signed out too. The PHP package signs only this browser out. See Signing In and Out.
From your own code, call Sessions::sign_out(), as SignIn::out(). It returns the user who was signed out, or None, and dispatches LoggedOut:
use laravel_keyring::Sessions; let user = Sessions::<Users>::sign_out(&auth, &session, &request, false).await?;true for its last argument leaves the remember token alone, as logoutCurrentDevice() does, but only use that where you answer straight away (see Services for Your Own Code). Your own auth.logout() ends the session's record too, once the handler returns, on routes in the web group.
The Verification Pipeline
Every verification, at login or step-up, runs through the PHP package's steps, in the same order: EnsureNotThrottled, VerifyFactor, ResolveDevice, EnsureNotRiskLocked, AssessRisk, DetermineRequirement and CompleteAttempt. What each does is in the PHP docs.
EnsureNotThrottled, VerifyFactor and CompleteAttempt are fixed places in the crate's code, wrapped around the others. The steps you can see and change are the four between them.
Customising the Steps
Change the pipeline with the provider's pipeline(), as Keyring::pipeline(). This adds a step after ResolveDevice and replaces AssessRisk:
use laravel_keyring::pipeline; KeyringServiceProvider::<Users>::new() .pipeline(|steps| steps.after(pipeline::RESOLVE_DEVICE, RefuseGuestNetwork).replace(pipeline::ASSESS_RISK, StrictRisk));before(), after(), replace() and remove() take a step's name: Keyring's are constants in pipeline (RESOLVE_DEVICE, ASSESS_RISK and the rest), and yours is its type's own name without its path unless name() says otherwise. A step that isn't there, or a step placed before VerifyFactor or after CompleteAttempt, stops the application booting. pipeline::names() lists the steps in order.
Mandatory Steps
EnsureNotRiskLocked and DetermineRequirement are mandatory: replace() and remove() refuse them, stopping the application booting. dangerously_replace() and dangerously_remove() change them anyway, as in the PHP package:
KeyringServiceProvider::<Users>::new() .pipeline(|steps| steps.dangerously_replace(pipeline::DETERMINE_REQUIREMENT, MyRequirement));Warning
dangerously methods log a warning at boot, pipeline::dangerously_changed_steps() lists them, and KeyringConformance fails until you acknowledge the step with acknowledge_dangerous_steps().
EnsureNotThrottled, VerifyFactor and CompleteAttempt can't be changed, even dangerously. A verification that would complete without its mandatory check having run, when that step wasn't dangerously changed, is refused with VerificationRefused and a critical verification_refused entry. A replacement that does the risk lock check itself marks it with context.risk_lock_checked, using risk::is_locked().
Writing a Step
A step implements laravel_keyring::pipeline::Step. It gets the Context and returns Flow::Next or Flow::Fail:
use laravel_keyring::pipeline::{Context, Flow, Handling, Step}; #[derive(Debug)]struct RefuseGuestNetwork; impl Step for RefuseGuestNetwork { fn handle<'a>(&'a self, context: &'a mut Context<'_>) -> Handling<'a> { Box::pin(async move { let guest = context.request.header("x-network") == Some("guest"); Ok(if guest { Flow::Fail } else { Flow::Next }) }) }}The context holds request, factor (the key), identifying (true for a sign in's first factor), attempt (the attempt as the policy sees it, with purpose), requirement (once DetermineRequirement has run) and risk_lock_checked, and context.user::<User>() gives the user. There's no authenticator, verification or outcome.
Flow::Fail refuses the verification as a wrong proof is refused, counting toward the rate limits but without FactorFailed. There's no $context->lockout(). Every verification runs the steps, a sign in's first factor, each answer on the challenge page and each confirm, so a step that should act once per sign in checks the attempt itself, as AssessRisk does (attempt.purpose == Purpose::Login && attempt.risk.is_none()). A factor checked inside another request, such as the password that adds a first second factor, doesn't run the steps. Context::new() makes a context to test a step with. The PHP package's Location::of() isn't public: read the location in a risk signal instead.
Responses
Each outcome is answered by a laravel_keyring::http::KeyringResponse, one for each of the PHP package's response contracts but FailedResponse and LockoutResponse:
| Variant | PHP Contract |
|---|---|
Authenticated { home, alerts } |
AuthenticatedResponse |
Registered { home, alerts } |
RegisterResponse |
Challenge { page, redirect } |
ChallengeResponse |
ConfirmationRequired { redirect } |
ConfirmationRequiredResponse |
EnrollmentRequired { redirect } |
EnrollmentRequiredResponse |
PasswordChangeRequired { redirect } |
PasswordChangeRequiredResponse |
SignedOut { reason } |
SignedOutResponse |
SignInToVerify |
SignInToVerifyResponse |
Logout |
LogoutResponse |
Status { status, data, redirect } |
StatusResponse |
Verified { just_now, home } |
VerifiedResponse |
What each answers is the PHP package's, as its docs describe. "JSON" means the request expects JSON and isn't an Inertia visit, which http::wants_json(&request) says.
Replace any of them with responses.respond_with(), a closure given the request and the response that returns None for the ones it leaves to Keyring:
use laravel::http::{IntoResponse, Redirect};use laravel_keyring::http::{KeyringResponse, wants_json}; config.section_mut::<KeyringConfig>().responses.respond_with(|request, response| match response { KeyringResponse::Logout if !wants_json(request) => Some(Redirect::to("/goodbye").into_response()), _ => None,});A refused sign in or step-up is laravel-rust's InvalidInput error rather than a FailedResponse or LockoutResponse to replace: render it your own way with laravel-rust's Errors::render. A browser's refusal on fields is given a 422 so laravel-rust redirects it back with the errors and the input, whatever status a JSON client gets, a lockout's 429 included.
Status Responses
Every action that isn't a sign in or confirmation answers with KeyringResponse::Status, with the PHP package's slugs, messages and data. Other requests are redirected, with the slug flashed as status, and the data flashed encrypted under keyring.result. Read it with http::result(&session, None), or one key with http::result(&session, Some("recoveryCodes")). http::status_message("password-updated") is a slug's message, in English.
Pages
Keyring renders the PHP package's pages, with the same props: login, challenge, confirm, register, forgot-password, verify-email, reset-password, email-verification, email-change, device-report and, with with_link(), sign-in-link. The props are in the PHP docs.
With the crate's inertia feature, and for a request that ran laravel-rust's Inertia middleware, each page renders the Inertia component auth/{name}, such as auth/login. Otherwise Keyring renders the view auth.{name}, given the props as its data, and a view that doesn't exist is a MissingPage error naming what it would get. An Inertia component that doesn't exist isn't checked for.
A JSON request for a page gets its name and props instead, as in the PHP package. With pages.enabled off, anything but JSON gets a 404.
Change a page's component with pages.page(), or answer it your own way with pages.render_using(), which is given the request and the props, and answers for JSON requests too:
let pages = &mut config.section_mut::<KeyringConfig>().pages; pages.page("challenge", "Auth/TwoFactor");pages.render_using("login", |_request, props| { Ok(laravel::http::IntoResponse::into_response(laravel::view::view("marketing.login", props)))});challenge and confirm are separate, so change confirm too. http::render(&request, name, props) renders one of Keyring's pages from a route of your own, as Keyring::render().
Routes
The paths are the PHP package's. laravel-rust's routes have no names.
| Method | URI | Purpose |
|---|---|---|
GET |
/login |
The login page. |
POST |
/login |
Sign in with a password. |
GET |
/login/passkey/options, /login/{factor}/options |
Options for a sign in without a username. |
POST |
/login/passkey, /login/{factor} |
Sign in with another primary factor. |
GET |
/auth/{provider}/redirect |
Sends the user to an identity provider. See Single Sign-On. |
GET |
/auth/{provider}/callback |
Where the provider sends the user back. |
GET |
/confirm/sso/redirect |
Sends a signed-in user to the provider for a step-up. |
GET |
/login/challenge/{factor?} |
The challenge page. |
POST |
/login/challenge/{factor} |
Verifies the next factor. |
POST |
/login/challenge/{factor}/send |
Sends a code. |
GET |
/login/challenge/email-code/link |
The page an emailed code's sign-in link opens, for any browser, signed in or not. Only with with_link(). |
POST |
/login/challenge/email-code/link |
That page's button: verifies the code, in the browser that started the sign in. Only with with_link(). |
GET |
/register |
The registration page. |
POST |
/register |
Creates an account. |
POST |
/logout |
Signs out. |
The registration routes exist only when features.registration is on, under the keyring limiter (limits.guest_forms, six a minute per address). The routes that spend session state take the session lock, as ->block() does in the PHP package, so parallel requests wait their turn: Laravel's 10 seconds to hold and 10 to wait. A request that waits the full 10 seconds gets a 500, not a 423.
Note
Your default cache store must support locks.
A signed-in browser at a guest page (/login, /register, the challenge page and the rest, but not the sign-in link's page) is redirected to home.
Events
The events are the PHP package's, in laravel_keyring::events, dispatched where the PHP package dispatches them: Attempting, FactorChallenged, FactorVerified, ProviderIdentityAccepted, FactorFailed, Lockout, VerificationRefused, AccountLocked, Authenticated, Confirmed, LoggedOut and SessionEnded. They carry plain values rather than the request or models: FactorFailed has the username that was typed, and Lockout and Attempting the factor. See Events.
Laravel's Login, Logout, Registered, Failed, Lockout and PasswordReset events aren't dispatched, as laravel-rust has none of them.