Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Sanctum Laravel Package

laravel/sanctum

Laravel Sanctum provides featherweight authentication for SPAs and simple APIs using token-based and session-based auth. Install it to secure your API routes with minimal configuration.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

  • Architecture fit: Sanctum is a first-party Laravel package, not a generic auth library. It fits two architectures cleanly: (1) a Laravel monolith or Laravel API serving a first-party SPA on the same top-level domain (cookie/session mode), and (2) simple machine-to-machine or mobile clients using opaque personal access tokens (token mode). It is a poor fit for third-party OAuth2/OIDC consumption, delegated authorization, or non-Laravel services — those are Passport or an external IdP concerns. If our architecture is Laravel + a decoupled SPA, this is the path of least resistance; if it is multi-service or partner-facing, it is the wrong primitive.
  • Integration feasibility: High. composer require laravel/sanctum, publish config/migration, add the HasApiTokens trait to the authenticatable model, and register the auth:sanctum guard. The personal_access_tokens table is polymorphic (since v0.2.0), so it supports multiple tokenable models without schema changes; multiple provider support (v2.4.0) covers multi-guard setups. Realistic effort for a competent Laravel team is days, not weeks — issuance endpoint, ability taxonomy, and revocation flow included.
  • Technical risk: Low-to-moderate and mostly lifecycle-shaped rather than defect-shaped. Majors are pinned to Laravel majors (v4 ↔ Laravel 11+, v3 ↔ Laravel 10, v2 ↔ Laravel 9), so every framework upgrade becomes a coordinated Sanctum upgrade. Functional gaps to plan around: no OAuth2 flows, no refresh tokens, no built-in token rotation, and no authorization model richer than string abilities (CheckAbilities / CheckForAnyAbility). Token-mode clients get long-lived opaque tokens unless we implement expiry and rotation ourselves. Recent releases show active maintenance (Laravel 13 support, PHP 8.4/8.5 compatibility, optional last_used_at tracking, indexes on personal_access_tokens, HMAC password-hash support), but the moderate score and dependents: 0 in the source data are a data-quality flag — validate adoption and CVE history directly against Packagist and the security policy before treating this as a low-scrutiny dependency.
  • Key questions:
    • Which mode per client: cookie/SPA, token, or both? This drives CORS, CSRF, and domain topology decisions.
    • Are any consumers outside our trust boundary (partners, third-party apps)? If yes, Sanctum is likely insufficient and Passport or an IdP should be evaluated now, not later.
    • What is the token lifetime, rotation, and revocation SLA? There is no built-in rotation — who owns that logic?
    • Multi-tenant or multi-guard requirements? Which models are tokenable?
    • What is the SPA/API domain topology (subdomains, separate registrable domains, localhost dev)? Stateful-domain misconfiguration is the single most common failure.
    • Do we need scoped authorization beyond coarse abilities, and who maintains the ability taxonomy?

Integration Approach

  • Stack fit: Laravel 11/12/13 on PHP 8.2–8.5, Composer-managed, standard relational backing store for tokens. Coexists with Laravel Octane, Horizon, and queued workloads (Octane instance-resolution issues were fixed in v2.11.2 — verify we are well past that). Cookie mode depends on the configured session driver, so Redis (or equivalent) should already be in the stack for horizontally scaled deployments.
  • Migration path: Three realistic paths. From session-only auth: additive — add the Sanctum guard and token endpoints without touching existing web sessions; both guards can run concurrently. From Passport or a JWT library: not a drop-in — token formats differ, so all clients must re-authenticate and be re-issued credentials; plan a dual-run window with both guards active and a client cutover. From no auth: greenfield, sequence token issuance first and expand abilities as endpoints are protected. In all cases, preserve the existing user table; the polymorphic token table avoids user-schema surgery.
  • Compatibility: Pin the Sanctum major to the Laravel major in composer.json and treat the pair as a single upgrade unit. Watch the PHP floor — v4.2.1 and v4.0.5 added PHP 8.5/8.4 support, so older pins will block runtime upgrades. Config files are published and app-local, so config/sanctum.php drift (stateful domains, guard list, expiration, last_used_at tracking) is a real upgrade hazard — diff it on every major. The text type change for the token name column and the added indexes in v4.2.0/v4.1.2 imply a migration on upgrade; budget for it on large token tables.
  • Sequencing:
    1. Install, publish config and migrations, run migrations in a non-production environment first.
    2. Decide per-client mode; configure stateful domains, CORS with credentials, and the CSRF cookie route for SPA clients.
    3. Add HasApiTokens and register the guard; wire auth:sanctum onto a single low-risk route as a canary.
    4. Build issuance, listing, and revocation endpoints; define the ability taxonomy and document it.
    5. Define token lifetime and rotation policy; add the sanctum:prune-expired scheduled command.
    6. Add observability (401/419 rates, token counts, prune job success) before broad rollout.
    7. Roll out route-by-route; keep the legacy guard active until client cutover is verified.

Operational Impact

  • Maintenance: Low ongoing burden relative to building auth in-house, but non-zero. Expect frequent patch releases and a major bump tracking each Laravel major; the upgrade work is concentrated in config/sanctum.php diffs, migration review, and regression testing of the stateful-domain and CSRF paths. Assign a named owner for the token lifecycle policy — that is our code, not the package's.
  • Support: MIT-licensed, no commercial SLA. Official Laravel documentation is good and the community is large; there is a published security policy for vulnerability reporting. Internal escalation still requires our own runbook for token revocation, mass invalidation (compromised client, departed employee), and incident response — the package gives primitives, not procedures.
  • Scaling: Token mode performs one indexed database read per authenticated request; at high request-per-second this becomes a database dependency on the hot path. Mitigations: read replicas, short-lived tokens with client re-issuance, or a caching layer in front of token validation via Sanctum::getAccessTokenFromRequestUsing/authentication callback hooks. last_used_at writes on every request are write amplification — the optional tracking config added in v4.3.0 should be evaluated and likely disabled on high-traffic endpoints. Cookie mode scales with the session store, so Redis sizing becomes the constraint; the CSRF cookie endpoint is cheap but must not be rate-limited into failures.
  • Failure modes:
    • 419 CSRF storms from misconfigured stateful domains or missing CORS credentials — the most common production incident; test the full domain matrix including staging and localhost.
    • 401 cascades from expired or revoked tokens with no client refresh path — the absence of refresh tokens means clients must re-authenticate, which is a UX and support-load decision to make deliberately.
    • Cookie/SameSite/domain breakage when SPA and API sit on different registrable domains — cookie mode effectively requires same-site topology or explicit cross-domain concessions.
    • APP_KEY rotation invalidates encrypted cookies and breaks cookie-mode sessions — must be sequenced with a session flush.
    • Database unavailability equals total auth outage; there is no offline or self-contained token validation.
    • Token table bloat if sanctum:prune-expired is not scheduled and monitored — degrades lookup performance and confuses audit queries.
    • Major-version drift leaving us on an unsupported Sanctum/Laravel pair with no security backports.
  • Ramp-up: Very low for Laravel-fluent engineers — hours to a day to first protected route, roughly a sprint to production-grade issuance, revocation, abilities, and pruning. Non-Laravel contributors face a steeper curve on guards, middleware ordering, and CSRF semantics. The real ramp-up cost is organizational, not technical: agreeing the ability taxonomy, token lifetime policy, and revocation runbook before the first integration ships.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
dbravoan/dbcms-admin-theme-dbcms
dbravoan/dbcms-theme-db-cyber
dbravoan/dbcms-blocks-basic
dbravoan/dbcms-module-content-audit
dbravoan/dbcms-module-ai-assistant
paygate-to/paygate-php
padosoft/askmydocs-connector-base
defstudio/supercharged-carbon
bernskioldmedia/laravel-matomo
bernskioldmedia/laravel-harvest
bernskiold/laravel-data-scrubber
bernskiold/laravel-currency-converter
bernskiold/laravel-campaign-monitor
bernskioldmedia/laravel-autotranslate
siberfx/telegram-bot
roy-sandip/laravel-view-extended
gregsphotography/site-builder-core
roy-sandip/laravel-view
anodyne/blade-fluentui-icons
webx-ui/module-catalog-collections