网页 综合 更新时间 2026-11-13 17:32:38

Laravel Sanctum | Laravel 13.x - The clean stack for Artisans and agents

自动蜘蛛 laravel.com 正文约 6000 字
Laravel Sanctum | Laravel 13.x - The clean stack for Artisans and agents
Laravel Sanctum provides a featherweight authentication system for SPAs (single page applications), mobile applications, and simple, token based APIs. Sanctum allows each user of your application to generate multiple API tokens for their account. These tokens may be granted abilities / scopes which specify which actions the tokens are allowed to perform.
Laravel Sanctum exists to solve two separate problems. Let's discuss each before digging deeper into the library.
First, Sanctum is a simple package you may use to issue API tokens to your users without the complication of OAuth. This feature is inspired by GitHub and other applications which issue "personal access tokens". For example, imagine the "account settings" of your application has a screen where a user may generate an API token for their account. You may use Sanctum to generate and manage those tokens. These tokens typically have a very long expiration time (years), but may be manually revoked by the user anytime.
Laravel Sanctum offers this feature by storing user API tokens in a single database table and authenticating incoming HTTP requests via the Authorization header which should contain a valid API token.
Second, Sanctum exists to offer a simple way to authenticate single page applications (SPAs) that need to communicate with a Laravel powered API. These SPAs might exist in the same repository as your Laravel application or might be an entirely separate repository, such as an SPA created using Next.js or Nuxt.
For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services. Typically, Sanctum utilizes Laravel's web authentication guard to accomplish this. This provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS.
Sanctum will only attempt to authenticate using cookies when the incoming request originates from your own SPA frontend. When Sanctum examines an incoming HTTP request, it will first check for an authentication cookie and, if none is present, Sanctum will then examine the Authorization header for a valid API token.
It is perfectly fine to use Sanctum only for API token authentication or only for SPA authentication. Just because you use Sanctum does not mean you are required to use both features it offers.
You may install Laravel Sanctum via the install:api Artisan command:
Next, if you plan to utilize Sanctum to authenticate an SPA, please refer to the SPA Authentication section of this documentation.
Although not typically required, you are free to extend the PersonalAccessToken model used internally by Sanctum:
Then, you may instruct Sanctum to use your custom model via the usePersonalAccessTokenModel method provided by Sanctum. Typically, you should call this method in the boot method of your application's AppServiceProvider file:
You should not use API tokens to authenticate your own first-party SPA. Instead, use Sanctum's built-in SPA authentication features.
Sanctum allows you to issue API tokens / personal access tokens that may be used to authenticate API requests to your application. When making requests using API tokens, the token should be included in the Authorization header as a Bearer token.
To begin issuing tokens for users, your User model should use the Laravel\Sanctum\HasApiTokens trait:
To issue a token, you may use the createToken method. The createToken method returns a Laravel\Sanctum\NewAccessToken instance. API tokens are hashed using SHA-256 hashing before being stored in your database, but you may access the plain-text value of the token using the plainTextToken property of the NewAccessToken instance. You should display this value to the user immediately after the token has been created:
You may access all of the user's tokens using the tokens Eloquent relationship provided by the HasApiTokens trait:
Sanctum allows you to assign "abilities" to tokens. Abilities serve a similar purpose as OAuth's "scopes". You may pass an array of string abilities as the second argument to the createToken method:
When handling an incoming request authenticated by Sanctum, you may determine if the token has a given ability using the tokenCan or tokenCant methods:
Sanctum also includes two middleware that may be used to verify that an incoming request is authenticated with a token that has been granted a given ability. To get started, define the following middleware aliases in your application's bootstrap/app.php file:
The abilities middleware may be assigned to a route to verify that the incoming request's token has all of the listed abilities:
The ability middleware may be assigned to a route to verify that the incoming request's token has at least one of the listed abilities:
For convenience, the tokenCan method will always return true if the incoming authenticated request was from your first-party SPA and you are using Sanctum's built-in SPA authentication.
However, this does not necessarily mean that your application has to allow the user to perform the action. Typically, your application's authorization policies will determine if the token has been granted the permission to perform the abilities as well as check that the user instance itself should be allowed to perform the action.
For example, if we imagine an application that manages servers, this might mean checking that the token is authorized to update servers and that the server belongs to the user:
At first, allowing the tokenCan method to be called and always return true for first-party UI initiated requests may seem strange; however, it is convenient to be able to always assume an API token is available and can be inspected via the tokenCan method. By taking this approach, you may always call the tokenCan method within your application's authorization policies without worrying about whether the request was triggered from your application's UI or was initiated by one of you
访问原文 返回搜索 https://laravel.com/framework/docs/sanctum
本页为82搜索生成的网页快照,内容来自站内索引;演示数据的原文链接仅作示例。