iqbalatma/laravel-jwt-auth

Laravel JWT 黑名单和刷新自定义机制

1.2.1 2023-08-19 06:47 UTC

This package is auto-updated.

Last update: 2024-09-19 09:18:58 UTC


README

Laravel jwt 使用来自 PHP-Open-Source-Saver / jwt-auth 的访问和刷新机制自定义

致谢

这是一个使用 PHP-Open-Source-Saver/jwt-auth 的包,该包是从 tymondesigns/jwt-auth 分支出来的。这个包只是抽象了 PHP-Open-Source-Saver/jwt-auth 并更改了刷新令牌的行为。

为什么你需要这个包?

PHP-Open-Source-Saver/jwt-auth 包只使用 1 个令牌(访问令牌)来获取受保护资源,而我需要 2 种类型的令牌(访问和刷新)。我用短 Ttl 制作访问令牌,用长 Ttl 制作刷新令牌。为什么我需要两种类型的令牌?当访问令牌被泄露时,它只有很短的时间访问,因此黑客有时间限制,并且不能重新调用新的令牌。在 PHP-Open-Source-Saver/jwt-auth 中,使用访问令牌来刷新令牌(重新调用新的令牌)的方式。我改变了这种行为,所以我们将有两种类型的令牌。因此,当黑客获取访问令牌时,他们不能重新调用新的令牌,因为需要刷新令牌。

另一种情况是,当你设置访问令牌为短 Ttl 时,你不能重新调用新的令牌,因为你需要一个有效的访问令牌。在这个包中,当你的访问令牌无效时,你仍然可以使用刷新令牌重新调用新的令牌

如何安装此包?

通过 composer 安装

composer require iqbalatma/laravel-jwt-auth

将服务提供者复制到 config/app.php

Iqbalatma\LaravelJwtAuth\Providers\LaravelServiceProvider::class,

使用以下命令发布供应商

php artisan vendor:publish --provider="Iqbalatma\LaravelJwtAuth\Providers\LaravelServiceProvider"

生成 jwt 密钥

php artisan jwt:secret

包准备就绪,可供使用

如何使用此包?

以下是使用此包的步骤

配置 Auth Config 守护者

修改你的 config/auth.php

<?php


    'defaults' => [
        'guard' => 'api',
        'passwords' => 'users',
    ],
    .....
    'guards' => [
        'api' => [
            'driver' => 'jwt',
            'provider' => 'users',
        ],
    ],

更新用户模型

修改你的模型合约并添加需要实现的方法

<?php

namespace App;

use Iqbalatma\LaravelJwtAuth\Contracts\Interfaces\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

在路由上使用中间件

以下是使用中间件保护路由的示例

<?php

  Route::get("users", [App\Http\Controllers\UserController::class, "index"])->middleware("api");

如何调用访问令牌和刷新令牌

以下是调用访问令牌和刷新令牌的步骤

<?php

use Iqbalatma\LaravelJwtAuth\Services\JWTService;

$jwtService = new JWTService();

$accessToken = $jwtService->invokeAccessToken($credentials);
$refreshToken = $jwtService->infokeRefreshToken();