📜  laravel composer sanctum - PHP (1)

📅  最后修改于: 2023-12-03 14:43:44.839000             🧑  作者: Mango

Laravel Composer Sanctum - PHP

Laravel Composer Sanctum is a package for Laravel that provides API authentication using tokens. It is built on top of Laravel's built-in authentication system and provides a simple way to authenticate your API with minimal setup.

Installation

To install Laravel Composer Sanctum, use Composer to require the package:

composer require laravel/sanctum

You can then run the migrations to create the necessary database tables:

php artisan migrate

Finally, add the Sanctum middleware to your api middleware group in app/Http/Kernel.php:

protected $middlewareGroups = [
    ...
    
    'api' => [
        ...
        
        \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];
Usage

Once you have installed and configured Sanctum, you can use it to authenticate API requests. To do this, you first need to create an API token for a user:

use App\Models\User;
use Laravel\Sanctum\HasApiTokens;

$user = User::find(1);
$user->createToken('token-name')->plainTextToken;

This will create a new API token for the user and return the plain text value of the token. You can then use this token to authenticate API requests:

curl -H "Authorization: Bearer <token>" http://example.com/api/user

To authenticate routes using Sanctum, you can use the auth:sanctum middleware:

Route::middleware('auth:sanctum')->get('/user', function () {
    return auth()->user();
});

This will ensure that the request is authenticated using Sanctum and will return the user associated with the API token.

Conclusion

Laravel Composer Sanctum provides a simple and secure way to authenticate API requests using tokens. It is easy to install and configure, and provides seamless integration with Laravel's built-in authentication system. If you are building an API with Laravel, then Sanctum is definitely worth exploring.