Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Authenticate with sessions, magic links, and Bearer tokens

Slabs puts explicit authentication helpers on ctx.auth and fixed-window rate limiting on ctx.rate_limit. Authentication never hides in route-group middleware. You call the exact guard you need on line 1 of each slab handler.

Choose an authentication guard

GuardAcceptsOn failure
ctx.auth.optional_session(&jar).await?Active session cookieReturns Ok(None)
ctx.auth.require_session(&jar).await?Valid session cookieHTTP 401 Unauthorized
ctx.auth.require_admin(&jar).await?Valid session with role == "admin"HTTP 401 or HTTP 403 Forbidden
ctx.auth.optional_auth(&jar, &headers).await?Authorization: Bearer token or session cookieReturns Ok(None)
ctx.auth.require_auth(&jar, &headers).await?Valid Bearer token or session cookieHTTP 401 Unauthorized
ctx.auth.require_write_auth(&jar, &headers).await?Valid Bearer token (permission == "write") or sessionHTTP 401 or HTTP 403 Forbidden

When a request includes an Authorization: Bearer ... header, optional_auth, require_auth, and require_write_auth validate only that Bearer token. They never fall back to the session cookie if the Bearer token is invalid.

When cookie_secure is true (the default in staging and production), Slabs names the session cookie __Host-slabs_session (Path=/, Secure, HttpOnly, SameSite=Lax, no Domain attribute). In local development over HTTP (cookie_secure == false), the cookie name is slabs_session.

Hash and verify passwords asynchronously with Argon2id

Your application owns its users table in migrations/. ctx.auth.hash_password, ctx.auth.verify_password, and ctx.auth.verify_password_constant_time are async functions. They offload Argon2id onto tokio::task::spawn_blocking with a concurrency semaphore and a 1024-byte password cap so slow hashes never block the async runtime.

Create a user and session cookie atomically inside one transaction:

#![allow(unused)]
fn main() {
use axum::{extract::State, http::StatusCode, Json};
use axum_extra::extract::CookieJar;
use chrono::Utc;
use serde::Deserialize;
use slabs::prelude::*;

#[derive(Debug, Deserialize)]
pub struct SignUpInput {
    pub email: String,
    pub password: String,
}

async fn handle(
    State(ctx): State<AppCtx>,
    jar: CookieJar,
    Json(input): Json<SignUpInput>,
) -> SlabResult<(StatusCode, CookieJar)> {
    let email = input.email.trim().to_lowercase();
    ctx.rate_limit.check(&format!("auth:signup:{email}"), 5, 300)?;

    let user_id = id::new("usr");
    let password_hash = ctx.auth.hash_password(&input.password).await?;
    let now = Utc::now().to_rfc3339();

    let mut tx = ctx.db.begin().await?;
    sqlx::query(
        "INSERT INTO users (id, email, password_hash, role, created_at)
         VALUES (?, ?, ?, 'member', ?)",
    )
    .bind(&user_id)
    .bind(&email)
    .bind(&password_hash)
    .bind(&now)
    .execute(&mut *tx)
    .await?;

    let (_session, cookie) = ctx
        .auth
        .create_session_in_tx(&mut tx, &user_id, "member", 30)
        .await?;
    tx.commit().await?;

    Ok((StatusCode::CREATED, jar.add(cookie)))
}
}

During sign-in, prefer ctx.auth.verify_password_constant_time(&input.password, stored_hash.as_deref()).await?. When stored_hash is None, it still runs an Argon2id check against a dummy hash so callers cannot measure response timing to enumerate registered emails. To verify against a known hash directly, call ctx.auth.verify_password(&input.password, &stored_hash).await?. To sign out, call let clear = ctx.auth.destroy_session(&jar).await?; and return jar.add(clear).

issue_magic_link generates a 6-character code from an unambiguous alphabet (omitting 0, O, 1, and I) and stores only a keyed domain-separated HMAC bound to (email, purpose) in slabs_magic_links:

#![allow(unused)]
fn main() {
// Step 1: Issue code and send email
ctx.rate_limit.check(&format!("magic:req:{email}"), 5, 300)?;
let issued = ctx.auth.issue_magic_link(&email, "sign_in", 15).await?;

ctx.mail
    .send(Email {
        from: String::new(),
        to: issued.email.clone(),
        subject: "Your sign-in code".into(),
        text_body: format!("Enter code {} within 15 minutes.", issued.code),
        html_body: None,
    })
    .await?;
}

When the user submits the code, pass email, purpose, and the submitted code to consume_magic_link. It strips non-alphanumeric characters, uppercases the code, verifies the keyed HMAC for (email, purpose), and executes DELETE ... RETURNING so every code works at most once. After 5 failed attempts within 15 minutes for the same (email, purpose), Slabs locks out the pair and deletes any pending codes.

#![allow(unused)]
fn main() {
// Step 2: Consume code atomically and start a session
ctx.rate_limit.check(&format!("magic:consume:{email}"), 20, 60)?;
let consumed = ctx
    .auth
    .consume_magic_link(&email, "sign_in", &input.code)
    .await?
    .ok_or_else(|| SlabError::unauthorized("invalid or expired code"))?;

// Look up or create the user for consumed.email, then create a session:
let (_session, cookie) = ctx.auth.create_session(&user_id, &role, 30).await?;
Ok((StatusCode::OK, jar.add(cookie)))
}

Issue and verify personal Bearer access tokens

Personal access tokens let CLIs, scripts, and AI agents call your endpoints without browser cookies. Tokens start with slb_ and are stored only as SHA-256 digests in slabs_access_tokens.

#![allow(unused)]
fn main() {
// Require a browser session to mint a new token
let session = ctx.auth.require_session(&jar).await?;
let issued = ctx
    .auth
    .issue_access_token(&session.user_id, &session.role, "CI deploy script", "write")
    .await?;
// Return `issued.token` once; plaintext tokens cannot be recovered later.
}

Protect API slabs with require_auth (read or write) or require_write_auth (requires permission == "write"):

#![allow(unused)]
fn main() {
async fn handle(
    State(ctx): State<AppCtx>,
    jar: CookieJar,
    headers: axum::http::HeaderMap,
) -> SlabResult<axum::Json<serde_json::Value>> {
    let principal = ctx.auth.require_write_auth(&jar, &headers).await?;
    Ok(axum::Json(serde_json::json!({
        "user_id": principal.user_id,
        "auth_kind": principal.auth_kind,
        "permission": principal.permission,
    })))
}
}

Rely on built-in CSRF, CORS, safe redirects, and safe blob responses

Slabs ships defense-in-depth protections enabled by default in slabs-http, slabs-html, and slabs-storage:

  • Fetch Metadata and Origin CSRF middleware runs on every cookie-authenticated POST, PUT, PATCH, and DELETE request (controlled by SLABS_CSRF_ENFORCE, default true). It rejects requests with Sec-Fetch-Site: cross-site and checks Origin against the request Host or SLABS_CORS_ORIGINS. Requests authenticated with Authorization: Bearer and inbound webhook paths (/webhooks*, /api/webhooks*) are exempt.
  • Cross-origin CORS stays disabled unless you set a comma-separated allowlist in SLABS_CORS_ORIGINS.
  • For explicit double-submit form tokens, call html::csrf_token(&ctx.auth, &session.id) when rendering and html::verify_csrf(&ctx.auth, &session.id, &form.csrf_token)? on submission.
  • htmx::redirect(path) and htmx::flash_redirect(...) validate that path is a safe relative path and fall back to "/" on open-redirect inputs such as //evil.com. For deliberate external URLs, call redirect_external(url) explicitly.
  • json_script("boot-data", &payload)? renders <script type="application/json"> with <, >, &, U+2028, and U+2029 escaped so user data cannot break out of the script tag.
  • BlobMeta::into_safe_response(bytes, allow_inline_passive) sets X-Content-Type-Options: nosniff, Content-Security-Policy: default-src 'none'; sandbox, and forces Content-Disposition: attachment for active file types such as image/svg+xml and text/html.

Mint and verify purpose-bound signed tokens

Use ctx.auth.sign_token and ctx.auth.verify_token for stateless, expiring tokens such as password resets, email verification links, and signed blob download URLs. sign_token encodes {"p": purpose, "exp": unix_ts, "d": payload} as unpadded URL-safe base64 and appends .<hex_hmac_sig> signed with SLABS_SECRET_KEY.

Because purpose sits inside the signed envelope, a token minted for "email_verify" fails verification on "password_reset" or "blob_download". verify_token returns HTTP 401 Unauthorized when the format, HMAC signature, payload shape, purpose, or expiration check fails.

#![allow(unused)]
fn main() {
use serde::{Deserialize, Serialize};
use std::time::Duration;

#[derive(Debug, Serialize, Deserialize)]
struct ResetClaims {
    user_id: String,
}

// Issue a 15-minute password reset token
let token = ctx.auth.sign_token(
    "password_reset",
    &ResetClaims { user_id: user.id.clone() },
    Duration::from_secs(900),
)?;

// Verify on submission
let claims: ResetClaims = ctx.auth.verify_token("password_reset", &input.token)?;
}

You can pair the same token flow with BlobMeta::into_safe_response for time-limited downloads:

#![allow(unused)]
fn main() {
let signed_blob_id: String = ctx.auth.verify_token("blob_download", &query.token)?;
if signed_blob_id != path_blob_id {
    return Err(SlabError::unauthorized("token does not match blob"));
}

let (meta, bytes) = ctx
    .storage
    .get(&path_blob_id)
    .await?
    .ok_or_else(|| SlabError::not_found("blob not found"))?;
Ok(meta.into_safe_response(bytes, true))
}

When you need signing or verification without a database handle (such as in unit tests), construct a stateless handle with Auth::for_signing(secret_key, cookie_secure).

Show one-shot flash banners across redirects

Use Flash, htmx::flash_redirect, htmx::take_flash, and html::flash_banner to carry feedback messages across POST-redirect-GET flows without storing UI state in SQLite.

Flash has four constructors (Flash::success, Flash::info, Flash::warning, Flash::error). Slabs serializes the message into an HMAC-signed slabs_flash cookie (HttpOnly, SameSite=Lax, Path=/, Max-Age=60, and Secure when cookie_secure is true).

In your mutation slab, return htmx::flash_redirect. It sets the signed cookie and responds with HTTP 303 See Other carrying both Location and HX-Redirect, so plain form posts and HTMX requests follow the redirect identically:

#![allow(unused)]
fn main() {
// slabs/settings/update_profile.rs
async fn handle(
    State(ctx): State<AppCtx>,
    jar: CookieJar,
    Form(input): Form<ProfileForm>,
) -> SlabResult<axum::response::Response> {
    let session = ctx.auth.require_session(&jar).await?;
    // ... update profile in SQLite ...

    Ok(htmx::flash_redirect(
        &ctx.auth,
        jar,
        "/settings",
        &Flash::success("Profile updated."),
    ))
}
}

In the destination GET slab, call htmx::take_flash(&ctx.auth, jar) to verify and clear the cookie in one step, render html::flash_banner(flash.as_ref()), and return the updated jar alongside your page:

#![allow(unused)]
fn main() {
// slabs/settings/show_settings.rs
async fn handle(
    State(ctx): State<AppCtx>,
    jar: CookieJar,
) -> SlabResult<(CookieJar, Markup)> {
    let _session = ctx.auth.require_session(&jar).await?;
    let (jar, flash) = htmx::take_flash(&ctx.auth, jar);

    let page = html::document(
        "Settings",
        &ctx.assets.stylesheet_urls(),
        &[],
        maud! {
            main class="mx-auto max-w-2xl p-6 space-y-4" {
                (html::flash_banner(flash.as_ref()))
                h1 { "Settings" }
            }
        },
    );

    Ok((jar, page))
}
}

html::flash_banner renders a Basecoat <div class="alert" role="status"> (with data-variant="destructive" for FlashKind::Error) when flash is Some, or empty markup when None. Tampered or expired cookies are discarded silently.

Enforce rate limits with proxy-aware client IPs

Call ctx.rate_limit.check(key, max_requests, window_secs)? at the top of any sensitive handler. When a key exceeds max_requests within window_secs, Slabs returns HTTP 429 Too Many Requests with a Retry-After header and JSON error body.

For unauthenticated endpoints such as login or password reset, extract the caller IP with client_ip(&headers, peer, ctx.config.trust_proxy):

#![allow(unused)]
fn main() {
use axum::extract::ConnectInfo;
use std::net::SocketAddr;

let ip = client_ip(&headers, Some(peer), ctx.config.trust_proxy);
ctx.rate_limit.check(&format!("auth:signin:{ip}"), 10, 300)?;
}

When SLABS_TRUST_PROXY=false (the default), client_ip ignores forwarding headers and uses the socket peer address so callers cannot spoof X-Forwarded-For. When SLABS_TRUST_PROXY=true behind a trusted reverse proxy (such as kamal-proxy, Fly Proxy, or Caddy), client_ip reads CF-Connecting-IP, Fly-Client-IP, or the rightmost valid IP in X-Forwarded-For.

RateLimiter stores fixed-window counters in process memory (capped at 50,000 entries) and prunes expired keys every 5 seconds.