📅  最后修改于: 2023-12-03 15:32:33.784000             🧑  作者: Mango
Laravel Sanctum is an official Laravel package for authentication and authorization of APIs. It provides a simple way to issue API tokens and authenticate API requests. Sanctum provides lightweight and intuitive API authentication.
Laravel Sanctum can be installed via Composer. Run the following command in your terminal:
composer require laravel/sanctum
After installation, you will need to migrate the database:
php artisan migrate
To use Sanctum, you will first need to define which model should be authenticated. You can do this by setting the $guard
property on your model:
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens; // Add this trait to your User model
.
.
.
}
Once you have set up your User
model, you can start issuing tokens to authenticate your API endpoints.
To issue a token, you can use the createToken
method on the user instance:
$token = $user->createToken('token-name')->plainTextToken;
This will create a new token and store it in the database. You can then use this token to authenticate API requests.
To authenticate an API request, you can add a middleware to your route:
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
Route::middleware([EnsureFrontendRequestsAreStateful::class])->group(function () {
// Your API routes here
});
This middleware will ensure that the API requests are authenticated using the token.
Laravel Sanctum is a great package for API authentication and authorization. With its simple and intuitive API, you can easily issue tokens to authenticate your API endpoints. The package seamlessly integrates with Laravel's built-in guard authentication system and Vue.js and React.js.
Give it a try and see how it can simplify API authentication in your Laravel application.