📅  最后修改于: 2023-12-03 14:47:12.900000             🧑  作者: Mango
Sanctum is a Laravel package that provides a simple and convenient way to implement token-based authentication in your PHP applications. It allows you to issue API tokens for your users, which can be used to authorize API requests.
To install Sanctum in your Laravel project, you can use Composer:
composer require laravel/sanctum
After installation, you need to publish the Sanctum configuration files:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Once the configuration files are published, you can migrate the Sanctum database tables:
php artisan migrate
To get started with Sanctum, you first need to configure your application to use the Sanctum middleware. You can do this by adding the EnsureFrontendRequestsAreStateful
middleware to your app/Http/Kernel.php
file:
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
protected $middlewareGroups = [
'web' => [
// ...
EnsureFrontendRequestsAreStateful::class,
],
];
To generate API tokens, you can use the createToken
method, which is available on the User
model:
use Illuminate\Support\Facades\Route;
use Laravel\Sanctum\Sanctum;
Sanctum::routes();
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
$user = App\Models\User::find(1);
$token = $user->createToken('API Token')->plainTextToken;
With Sanctum, you can protect your API routes using the auth:sanctum
middleware:
Route::middleware('auth:sanctum')->group(function () {
// Protected routes here
});
And that's it! You now have token-based authentication set up in your Laravel application using Sanctum.
For more details and advanced usage, please refer to the official Sanctum documentation.
Markdown code formatting:
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
protected $middlewareGroups = [
'web' => [
// ...
EnsureFrontendRequestsAreStateful::class,
],
];
use Illuminate\Support\Facades\Route;
use Laravel\Sanctum\Sanctum;
Sanctum::routes();
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
$user = App\Models\User::find(1);
$token = $user->createToken('API Token')->plainTextToken;
Route::middleware('auth:sanctum')->group(function () {
// Protected routes here
});
Official Sanctum Documentation