Weave Code
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 is a lightweight authentication package for Laravel, ideal for SPAs and simple APIs. It supports cookie-based session auth for first-party SPAs and API tokens for personal access tokens, with minimal configuration and Laravel-first integration.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Lightweight Authentication: Sanctum is purpose-built for SPAs (Single-Page Applications) and simple APIs, aligning perfectly with Laravel’s ecosystem. It avoids the overhead of Passport (Laravel’s OAuth2 package) while providing essential token-based auth features.
  • Stateless & Stateful Modes: Supports both stateless (API tokens) and stateful (session-like) authentication, making it versatile for hybrid architectures (e.g., SPAs + traditional server-rendered apps).
  • Laravel Integration: Designed as a first-class citizen of Laravel, leveraging Eloquent, middleware, and Laravel’s routing system. Minimal abstraction means deep compatibility with Laravel’s conventions.
  • Token Management: Built-in token expiration, revocation, and scope-based authorization simplify compliance and security requirements.

Integration Feasibility

  • Minimal Boilerplate: Installation via Composer (laravel/sanctum) and a single php artisan vendor:publish command suffices. Migration and model setup are automated.
  • Middleware-First: Uses Laravel’s middleware pipeline (auth:sanctum) for seamless API protection, reducing custom logic.
  • CSRF Protection: Built-in CSRF token handling for stateful requests (e.g., SPAs using cookies), aligning with Laravel’s security defaults.
  • Customization Points:
    • Token retrieval logic (getAccessTokenFromRequestUsing).
    • Guard configuration (supports multiple guards).
    • Token naming conventions (e.g., personal_access_tokens table).
    • Stateful domain whitelisting (e.g., sanctum.stateful config).

Technical Risk

  • Database Schema: Relies on a personal_access_tokens table. Pre-existing apps must handle migrations or schema conflicts (though Sanctum provides them).
  • Token Storage: Tokens are stored in the database. For high-scale APIs, consider:
    • Performance: Indexes on tokenable_id, name, and abilities (added in v4.2.0) mitigate lookup overhead but may need tuning for large-scale deployments.
    • Scaling: Stateless tokens are cache-friendly, but stateful sessions (cookies) require session storage (e.g., Redis) for horizontal scaling.
  • SPA-Specific Quirks:
    • Cookie-based stateful auth requires CORS and SameSite cookie attributes to be configured correctly.
    • Token leakage risks if frontend storage (e.g., localStorage) is compromised (mitigated by short-lived tokens/expiration).
  • Laravel Version Lock: Tight coupling with Laravel versions (e.g., v4.x requires Laravel 11+). Downgrading Laravel may break compatibility.
  • Deprecations: Some methods (e.g., MissingScopeException) are deprecated; review changelog for breaking changes in future upgrades.

Key Questions

  1. Use Case Clarity:
    • Is this for a pure SPA, hybrid app, or simple API? Sanctum’s stateful mode may add unnecessary complexity for headless APIs.
    • Do you need OAuth2 (e.g., third-party auth)? Sanctum is not a replacement for Passport.
  2. Token Lifecycle:
    • How will tokens be revoked (e.g., on password change)? Sanctum supports manual revocation but lacks built-in hooks.
    • Should tokens expire automatically? Sanctum supports expires_at but requires manual cleanup (e.g., via Laravel Queues).
  3. Scaling Needs:
    • Will the app handle millions of tokens? Consider Redis for token storage or caching.
    • Is horizontal scaling required? Stateful sessions need shared storage (e.g., Redis).
  4. Security:
    • How will token theft be mitigated (e.g., short TTL, device fingerprinting)?
    • Are scopes/abilities needed for fine-grained access control?
  5. Migration Path:
    • Are you replacing an existing auth system (e.g., JWT, Passport)? Assess data migration needs (e.g., personal_access_tokens table).
    • Will frontend teams need guidance on cookie/session management (e.g., SameSite, Secure flags)?

Integration Approach

Stack Fit

  • Laravel Ecosystem: Ideal for Laravel-based stacks (PHP 8.1+, Laravel 11+). Leverages:
    • Eloquent for token storage.
    • Middleware for auth logic.
    • Laravel’s routing and HTTP clients.
  • Frontend Compatibility:
    • SPAs: Works with React, Vue, Next.js (via fetch/axios with cookies or tokens).
    • Traditional Apps: Stateful mode uses cookies; stateless mode uses Authorization: Bearer headers.
  • Database: Supports MySQL, PostgreSQL, SQLite (via Laravel migrations). No external dependencies beyond Laravel’s DB layer.
  • Caching: Optional Redis integration for token revocation or session storage.

Migration Path

  1. Assessment Phase:
    • Audit existing auth flows (e.g., JWT, session-based, or custom tokens).
    • Identify token storage (DB, cache) and revocation mechanisms.
  2. Setup:
    • Install Sanctum:
      composer require laravel/sanctum
      php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
      php artisan migrate
      
    • Configure config/sanctum.php (e.g., stateful domains, token TTL).
  3. Incremental Rollout:
    • Phase 1: Replace legacy token logic with Sanctum’s HasApiTokens trait.
    • Phase 2: Migrate endpoints to use auth:sanctum middleware.
    • Phase 3: Update frontend to use Sanctum tokens (cookies or headers).
  4. Deprecation:
    • Phase out old token tables/middleware.
    • Use Sanctum’s tokenCant() or tokenCan() for access control.

Compatibility

  • Laravel Versions: Sanctum v4.x supports Laravel 11–13. Downgrade to v3.x for older Laravel versions.
  • PHP Versions: PHP 8.1+ (v4.x supports up to 8.5).
  • Frontend Frameworks: Agnostic but requires:
    • SPAs: Cookie handling (e.g., axios with credentials) or token storage.
    • Mobile Apps: Custom token storage (e.g., Keychain, Secure Storage).
  • Third-Party Services: Works with Laravel’s HTTP clients (e.g., Guzzle) for inter-service auth.

Sequencing

  1. Backend First:
    • Set up Sanctum in a staging environment.
    • Test token generation/revocation with Laravel Tinker or Postman.
  2. API Contracts:
    • Define token response formats (e.g., access_token, token_type).
    • Document frontend requirements (e.g., cookie attributes).
  3. Frontend Integration:
    • Update API calls to include Authorization headers or cookies.
    • Implement token refresh logic (Sanctum lacks built-in refresh tokens; use custom endpoints).
  4. Security Hardening:
    • Restrict stateful domains to trusted origins.
    • Enable token expiration and cleanup jobs.
  5. Monitoring:
    • Log token usage (e.g., last_used_at).
    • Monitor failed auth attempts for anomalies.

Operational Impact

Maintenance

  • Updates: Sanctum follows Laravel’s release cycle. Minor updates (e.g., v4.x) are low-risk; major versions may require testing.
  • Configuration: Centralized in config/sanctum.php (e.g., token TTL, stateful domains).
  • Logging: Minimal built-in logging; extend with Laravel’s logging channels for token events.
  • Backups: Critical for personal_access_tokens table (contains sensitive data).

Support

  • Troubleshooting:
    • Common issues: CORS misconfigurations, cookie attributes, or token lookup failures.
    • Debug tools: php artisan tinker to inspect tokens; Sanctum::resolveToken() for custom token retrieval.
  • Documentation: Official Laravel docs are comprehensive but assume familiarity with Laravel’s internals.
  • Community: Active GitHub issues and Laravel forums for niche problems.

Scaling

  • Stateless Tokens:
    • Performance: Database indexes on tokenable_id and name improve lookup. For high volume, consider:
      • Redis: Cache tokens or use Redis for storage (via custom TokenRepository).
      • Read Replicas: Offload token queries to replicas.
    • Throughput: Short tokens (60 chars) reduce payload size.
  • Stateful Sessions:
    • Shared Storage: Use Redis or database sessions for horizontal scaling.
    • Cookie Overhead: Stateful mode increases payload size (cookies vs. headers).
  • Token Revocation:
    • Bulk Operations: Sanctum lacks built-in bulk revocation; implement via queries or Laravel Queues.
    • Real-Time: Use Laravel Events or WebSockets to notify clients of revoked tokens.

Failure Modes

Failure Scenario Impact Mitigation
Database downt
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai