Laravel Sanctum
repository·4.x·Indexed 25 days ago
https://github.com/laravel/sanctumA featherweight authentication system for Single Page Applications (SPAs) and simple APIs. It provides lightweight authentication without the complexity of full OAuth2 implementations, featuring personal access tokens, stateful domain configuration for SPAs, and token ability verification. Includes tools for pruning expired tokens via the `sanctum:prune-expired` command and customizable guards and middleware.
What's inside Laravel Sanctum
- Laravel Sanctum is a featherweight authentication system designed specifically for Single Page Applications (SPAs) and simple APIs. It provides a lightweight way to handle authentication without the complexity of full OAuth2 implementations.
Upgrade to Sanctum 4.0 from 3.x
4.xWhen upgrading to Sanctum 4.0, ensure your environment meets the new minimum requirements:
- Minimum PHP Version: PHP 8.2
- Minimum Laravel Version: Laravel 11.0
Publish Sanctum migrations in Sanctum 4.0
4.xIn Sanctum 4.0, migrations are no longer automatically loaded from the package's internal directory. You must manually publish them to your application's migration directory by running the following command:
php artisan vendor:publish --tag=sanctum-migrationsUpdate Sanctum 4.0 middleware configuration
4.xIn Sanctum 4.0, you must update the
middlewarearray in yourconfig/sanctum.phpfile to use the fully qualified class names forauthenticate_session,encrypt_cookies, andvalidate_csrf_token.'middleware' => [ 'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class, 'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class, 'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class, ],Publish Sanctum configuration and migrations
4.xTo customize Sanctum's behavior or manage its database schema, you can publish its configuration file and migration files using the following Artisan commands:
- Migrations:
php artisan vendor:publish --tag=sanctum-migrations - Configuration:
php artisan vendor:publish --tag=sanctum-config
- Migrations:
Configure Sanctum session guards
4.xThe
AuthenticateSessionmiddleware uses thesanctum.guardconfiguration key to determine which authentication guards should be monitored for session validity. This middleware ensures that if a user's password changes, their existing sessions are invalidated across the specified guards.You can define one or more guards in your
config/sanctum.phpfile.Configure the Sanctum guard via sanctum.guard
4.xThe SanctumGuarditerates through a list of authentication guards defined in your configuration to resolve the user. You can specify which guards Sanctum should check by setting thesanctum.guardconfiguration key. This value can be a single string or an array of strings. By default, it uses thewebguard.Configure stateful domains for SPA authentication
4.xTo enable stateful authentication for your Single Page Application (SPA), you must define your frontend domains in the
sanctum.statefulconfiguration array. TheEnsureFrontendRequestsAreStatefulmiddleware uses this list to determine if an incoming request should be treated as a first-party request, enabling session-based authentication and CSRF protection.If you use a placeholder for the current host, you can use
Sanctum::$currentRequestHostPlaceholder(though typically you will list specific domains likefrontend.example.com).Customize access token authentication
4.xUseauthenticateAccessTokensUsingto provide a custom callback for authenticating access tokens. This allows you to override the default logic used to validate the token against the database.Act as a user with specific abilities (Testing)
4.xTheactingAsmethod allows you to mock an authenticated user with a specific set of token abilities. This is primarily used in testing environments to simulate requests made by a user with certain permissions.Use CheckScopes middleware (Deprecated)
4.xThe
CheckScopesmiddleware is used to verify if an incoming request's token possesses all the required scopes.Note: This middleware is deprecated. You should use
Laravel\Sanctum\Http\Middleware\CheckAbilitiesinstead.CheckScopesinternally callsCheckAbilitiesand re-throwsMissingAbilityExceptionas aMissingScopeException.Access the owner of a PersonalAccessToken
4.xThetokenablerelationship allows you to retrieve the model instance (e.g., aUser) that the access token belongs to using a polymorphic relationship.