Luis Cobucci JWT 适配 Laravel 使用

dev-master 2023-04-19 05:25 UTC

This package is auto-updated.

Last update: 2024-09-19 08:34:23 UTC


README

一个用于适配 Laravel 和 Lumen 的 JSON Web Token 库,基于 lcobucci/jwt

它使用非对称算法,使用 私钥 进行签名创建,使用 公钥 进行验证。这意味着你可以分发你的 公钥。然而,私钥 应该 保密

Laravel 安装

通过 composer

composer require adrianoalves/jwt

安装包

php artisan jwt:install

生成私钥和公钥

php artisan make:jwt-keys

根据需要修改你的配置文件中的 jwt.php,如果需要,添加你的应用程序的策略。

将 auth.php 配置文件中的路由驱动更改为 jwt。

'guards' => [
    'jwt' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

Auth Guard 使用

路由

Route::middleware('auth:jwt')->get('/user', function (Request $request) {
    return $request->user();
});

// if you set jwt as driver for your api guard
Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

登录

// Generate a token for the user if the credentials are valid
$token = Auth::attempt($credentials);

用户

// Getting the currently authenticated user
$user = Auth::user();