Sanctum for Laravel Rust: API tokens and SPA auth, rebuilt natively in Rust
Laravel Sanctum is the standard way to authenticate API tokens and first-party single-page apps in Laravel PHP. It has two modes: personal access tokens for API clients, and cookie-based auth for a first-party SPA.
Laravel Rust 0.1.4, the Rust port by Taylor Otwell, has session auth and a RequestGuard pattern, but no personal-access-token model and no SPA mode. rupirate-sanctum fills that gap. It is a native Rust crate, written from scratch, that brings both Sanctum modes to Laravel Rust.
It is part of rupirate, a set of Laravel packages rebuilt natively in Rust. Version 0.2.0 is on crates.io. The full guide lives in DOCUMENTATION.md.
What you get:
- Personal access tokens with abilities and expiry
- A bearer-token guard that plugs into the framework's auth
- Abilities middleware
- Cookie-based SPA auth: stateful domains, a csrf-cookie endpoint, and a dual-mode guard
- Test helpers, token hooks, and an auth event
Install
From crates.io:
[dependencies] rupirate-sanctum = "0.2.0" Or from a local checkout of the repo:
[dependencies] rupirate-sanctum = { path = "../rupirate-sanctum" } Register the provider:
Application::configure().with_providers(|providers| { providers.add(rupirate_sanctum::SanctumServiceProvider); }) Then run migrate once. The package ships two migration files. The first creates the personal_access_tokens table. The second adds indexes on (tokenable_type, tokenable_id) and on expires_at, the columns the token lookups need. The table holds id, tokenable_type, tokenable_id, name, token (unique), abilities, last_used_at, expires_at, and timestamps. Migrations in this framework are forward-only, so there is no down migration.
Issue a token
Create a token for a user. The plaintext is shown once. You cannot recover it later. Only the SHA-256 hash of the secret is stored.
let sanctum = app.resolve::<Sanctum>().await; let created = sanctum .create_token(&user, "ci-deploy", &["read"], None) .await?; // show created.plain_text_token now, e.g. `1|aB3...` The plaintext looks like 1|aB3.... The 1 is the token id. The rest is the secret: an optional prefix, 40 random characters, and an 8-character checksum. Pass an explicit expiry to create_token to override the default for one token.
Protect a route
The guard is per user type, so the application registers it as a service:
Application::configure() .with_services(|services| { services.singleton(|_| async move { Ok(SanctumGuard::<User>::new()) }); }) .with_routing(|routing, _| { routing.api(|route| { route .middleware(Authenticate::via::<SanctumGuard<User>>()) .middleware(CheckAbilities::new(["servers:create"])) .group(|route| { route.post("/servers", servers::store); }); }); }) Put the guard middleware before the abilities middleware. The abilities middleware reads the token id the guard stashed. Placed first, it sees no token and every request gets a 403.
In a handler, the authenticated user is available as an extractor:
async fn me(user: Authenticated<User>) -> String { user.0.email.clone() } A request the guard cannot authenticate gets a 401. A request with no token, or a token missing an ability, gets a 403.
How a token works
A token's plaintext is {id}|{secret}. The secret is the configured prefix, 40 random alphanumeric characters, and an 8-character crc32b checksum. The format matches upstream Laravel, so a truncated or mistyped token is easy to spot. The checksum is not a secret and is not verified on lookup. The stored SHA-256 hash is the check.
The row stores the hash, the owning user's type and id, a name, abilities as a JSON array, and optional last_used_at and expires_at timestamps. A leaked database never reveals a usable token. The secret is a 40-character CSPRNG value, about 238 bits, so offline brute force is infeasible.
Tokens issued before 0.2.0 still authenticate. They have a 40-character secret with no prefix or checksum. The lookup hashes whatever secret is presented, so old tokens keep working.
When the guard runs, it reads the Authorization: Bearer token, checks the secret against the stored hash in constant time, rejects expired tokens and bearer tokens over 256 characters (plus the prefix length), refreshes last_used_at unless SANCTUM_REFRESH_LAST_USED_AT is off, verifies the token belongs to the guard's user type, loads the user, and stashes the token id in the request context. Handlers reload the token with Sanctum::current_token(), which re-checks expiry on every call.
Abilities
Abilities are exact, case-sensitive strings. "read", "Read", and "read " are three different abilities. "*" grants everything. Never pass user input through as abilities.
CheckAbilities requires every listed ability. CheckAbility requires at least one. An empty ability list denies everything. CheckAbilities::new([]) lets nothing through. If a route needs no ability check, do not attach the middleware at all.
On the token itself, can checks one ability and cant is the inverse:
let token = sanctum.current_token().await?.unwrap(); if token.can("servers:create") { // ... } if token.cant("servers:delete") { // ... } create_token validates its inputs: the name is capped at 255 characters, at most 100 abilities, each at most 255 characters and never empty.
SPA authentication
For a first-party single-page app, Sanctum also authenticates by session cookie. The SPA and the API share the domain. They may be different subdomains.
The flow:
- Set the SPA's origin in
SANCTUM_STATEFUL_DOMAINS(comma-separated). The default is the localhost list, for local development. - The SPA calls
GET /sanctum/csrf-cookiebefore logging in. The response sets theXSRF-TOKENcookie. The provider registers this route whenroutesis on, which is the default. - The SPA logs in through the app's normal session login. Later requests carry the session cookie.
- On the API routes, attach
EncryptCookiesandEnsureFrontendRequestsAreStatefulbefore the guard:
use laravel::cookie::EncryptCookies; use rupirate_sanctum::EnsureFrontendRequestsAreStateful; routing.api(|route| { route .middleware(EncryptCookies::default()) .middleware(EnsureFrontendRequestsAreStateful) .middleware(Authenticate::via::<SanctumGuard<User>>()) .group(|route| { route.get("/me", me); }); }); The guard then authenticates a first-party request from the session. A transient token with ["*"] is stashed, so current_token() returns a token and tokenCan is always true. A request from anywhere else never consults the session, so a third-party site cannot ride a logged-in user's session.
A bearer token still works on the same routes, with or without an Origin header. The guard tries, in order: a test's acting_as, a first-party session, then the bearer token.
The EncryptCookies gotcha
EncryptCookies is required on API routes, and it must come before the stateful middleware. The session cookie is encrypted, and the session cannot be read from an encrypted cookie. Without it, first-party requests silently get a fresh empty session and a 401. The web group already includes it, so API routes in the web group do not need this middleware for the session.
CSRF
A state-changing session request, anything but GET, HEAD, or OPTIONS, must also pass a CSRF check. It passes with the Sec-Fetch-Site: same-origin header, or a token matching the session's CSRF token in the X-CSRF-TOKEN header (plain) or the X-XSRF-TOKEN header (the encrypted XSRF-TOKEN cookie value, as JavaScript sends it). A failed CSRF check is a 419. The _token form field is not read, so form clients send the token in a header.
In the browser, the flow looks like this:
// Get the CSRF cookie first. await fetch("https://api.example.com/sanctum/csrf-cookie", { credentials: "include", }); // Then call the API with the session cookie attached. const me = await fetch("https://api.example.com/me", { credentials: "include", }); Testing
Authenticate as a user in a feature test without issuing a real token:
let sanctum = app.resolve::<Sanctum>().await; sanctum.acting_as(&user, &["read"]); // requests are now authenticated as this user, with a transient // token carrying ["read"] sanctum.stop_acting_as(); // guests again acting_as is for tests only. It lives on the service until stop_acting_as or the application is dropped, and it never touches the database. Production code that calls it authenticates every later request as that user. The guard loads the user from the acting-as id and checks the user type, so a deleted user becomes a guest, not a stale user.
Token hooks
Two hooks let the application customise how tokens are found and whether they authenticate. They match upstream Laravel's getAccessTokenFromRequestUsing and authenticateAccessTokensUsing:
// Find the token somewhere other than the Authorization header. sanctum.set_token_retrieval_callback(|request| { request.header("x-api-token").map(str::to_owned) }); // Refuse a valid token (returning false), or allow it (true). // The callback cannot admit a token that failed Sanctum's checks. sanctum.set_token_authentication_callback(|token, valid| { valid && token.name != "suspended" }); A retrieval callback that returns None falls back to the bearer header. Never accept a token from a place an attacker can set without the user knowing, such as a query parameter on a GET that a browser follows.
Events
A successful bearer-token authentication fires a TokenAuthenticated event carrying the token row (hash only, never the plaintext). Listen for it to record a token's last-seen IP or alert on a new device:
use laravel::event::Event; use rupirate_sanctum::TokenAuthenticated; async fn on_token_authenticated(event: Event<TokenAuthenticated>) { let _ = event.token.id; } Session-authenticated (SPA) requests and acting_as do not fire it. Those are not token authentications. A listener that fails does not fail the request.
Finding and revoking tokens
sanctum.find_token(plain_text_token).await?; // None when unknown, wrong, or expired sanctum.revoke(token).await?; // revoke one token (a transient token is a no-op) sanctum.revoke_all_for(&user).await?; // revoke all of a user's tokens sanctum.list_tokens_for(&user).await?; // a user's tokens, oldest first sanctum.revoke_for_user(&user, token_id).await?; // revoke one of a user's tokens by id sanctum.revoke_all_for_type("app::models::User", "42").await?; // by stored type + id sanctum.current_token().await?; // the current request's token (transient for SPA) list_tokens_for is how an operator finds the leaked token to revoke. The rows carry only the stored hash, never the plaintext, so they are safe to show the user. revoke_for_user is scoped to the user, so it cannot touch another user's token. revoke_all_for_type is the escape hatch for tokens orphaned by a user-model move or a deleted user. Call revoke_all_for before deleting a user, or the tokens are orphaned.
Pruning expired tokens
$ laravel sanctum:prune-expired $ laravel sanctum:prune-expired --hours 48 sanctum:prune-expired deletes tokens that expired more than 24 hours ago (upstream Laravel's default) and prints how many were pruned. --hours changes the window. --hours 0 deletes every expired token. When SANCTUM_EXPIRATION is set, tokens created more than expiration + hours ago are deleted too, even when they have no expiry of their own. Run it on a schedule. Daily is enough. Tokens without an expiry are never pruned by the default run. The same thing is available in code as Sanctum::prune_expired() and Sanctum::prune_expired_older_than(hours).
Configuration
| Setting | Env | Default |
|---|---|---|
Token lifetime, in minutes (0 = never expires) | SANCTUM_EXPIRATION | 0 |
Refresh last_used_at on each authentication | SANCTUM_REFRESH_LAST_USED_AT | true |
| First-party origins for SPA auth, comma-separated | SANCTUM_STATEFUL_DOMAINS | localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1 |
| Prefix for new token secrets | SANCTUM_TOKEN_PREFIX | (empty) |
Register the csrf-cookie route | SANCTUM_ROUTES | true |
URL prefix for the csrf-cookie route | SANCTUM_PREFIX | sanctum |
Pass an explicit expiry to create_token to override the default for one token. Turn SANCTUM_REFRESH_LAST_USED_AT off on read-heavy APIs or on SQLite: every authentication then stops performing a database write, so concurrent requests no longer serialize on the token row's write lock.
The app URL (APP_URL) is read for Sanctum::current_application_url_with_port, but it is NOT added to the stateful list automatically. Add the production domain to SANCTUM_STATEFUL_DOMAINS explicitly.
Security notes
- The guard is strict about the user type. A token authenticates only the user type it was minted for (
tokenable_typemust equal the guard's model). A token minted forUsernever authenticates asAdmin, even when both are id 1. There is no opt-out. An app relying on cross-type auth was relying on a bug. - Audit logging uses the
logfacade. Token creation, auth success (debug), auth failure (warn, with id and reason), cross-type rejection (warn), and revocation and pruning (info) are logged. No log line ever carries a token or secret value. - A stolen bearer token is fully usable. There is no token binding (no DPoP or mTLS). Treat tokens like passwords: set an expiry, watch the auth-failure logs, and revoke on suspicion.
- The crate has no rate limiting of its own on the bearer path. Rate-limit bearer-guarded routes with the framework's throttle middleware, and monitor auth failures.
- The stored hash is skipped by serde, so it cannot leak into a JSON response by mistake. But the
#[model]macro derivesDebugunconditionally, which this crate cannot override, so never print a token with{:?}into a log line. -
tokenable_typeis the model's full module path (for exampleapp::models::User). Moving the model to another module changes the stored name, andrevoke_all_forthen matches nothing for the old tokens. Userevoke_all_for_typewith the old name, or re-issue the tokens.
What it does not do
- No custom token model. Upstream PHP has
usePersonalAccessTokenModel. This crate does not. The token model is a concrete#[model]struct, and making the crate generic over it would be a breaking change. The token hooks are the way to customise token auth. - No
sanctum.guardconfig. The framework has one session guard per application, and the guard checks the session for its own user type. - No
AuthenticateSessionmiddleware. The framework's session guard already invalidates sessions on password change. - The design decisions are the author's defaults. The security choices above (strict type check, empty list denies, never-expire default,
logfacade) are defaults the application can override by changing the behaviour described. They were not voted on or approved by users. If a default does not fit your app, change it and say so in your own docs.
One break in 0.2.0
Version 0.2.0 added fields to SanctumConfig, so an exhaustive SanctumConfig { ... } literal breaks. Build configs with ..Default::default() to stay forward-compatible. Existing tokens are unaffected: pre-0.2.0 tokens still authenticate.
Tests
The crate ships 61 tests: 8 lib unit, 18 package, 20 red-team, 8 SPA, and 7 doctests. The red-team suite covers the attack surfaces: cross-type auth, empty ability lists, expired tokens, corrupt abilities JSON, and the SPA paths (third-party origin, missing CSRF token, wrong CSRF token). Clippy reports 0 warnings.
Wrapping up
rupirate-sanctum brings both Laravel Sanctum modes to Laravel Rust: personal access tokens with abilities and expiry, and cookie-based SPA auth with a dual-mode guard. Install it from crates.io, read the full guide in DOCUMENTATION.md, and find the source on GitHub under rupirate/rupirate-sanctum.