chantouch/laravel-jwt-redis

此包允许使用JWT进行身份验证的用户在Redis中以他们的角色、权限、状态以及任何您想要的任何内容进行存储和管理。

v3.2.1 2024-04-04 11:17 UTC

This package is auto-updated.

Last update: 2024-09-04 12:10:56 UTC


README

此包允许使用JWT进行身份验证的用户在Redis中以他们的角色、权限、状态以及任何您想要的任何内容进行存储和管理。

此包最初是从 sametsahindogan/laravel-jwtredis 分支出来的。

此外,此包还有一个观察器,用于监听和更新Redis中的用户模型。当您为用户分配角色和权限,或更新和删除用户模型时,此观察器会被触发。

要求

此包与 php-open-source-saver/jwt-authspatie/laravel-permission 包协同工作。

# 请确保安装和配置这些依赖项。您必须发布、迁移等所有包。 #

安装

composer require chantouch/laravel-jwt-redis

完成此步骤后,您需要将以下值添加到 .env 文件中

CACHE_DRIVER=redis
REDIS_CLIENT=predis

接下来,您需要按照以下方式更改您的 config/auth.php 配置文件中的 guardsproviders 数组

<?php
return [
'guards' => [
        'api' => [
            'driver' => 'jwt_redis',
            'provider' => 'users'
        ],
    ],

'providers' => [
        'users' => [
            'driver' => 'jwt_redis_user',
            'model' =>  App\Models\User::class, /* Your User Model */
        ],
    ],
];

此包使用自动发现来注册服务提供者,但如果您想手动完成,服务提供者是:将以下内容添加到您的 config/app.php 配置文件中的 providers 数组

Chantouch\JWTRedis\JWTRedisServiceProvider::class,

您可以使用以下命令发布配置

php artisan vendor:publish --provider='Chantouch\JWTRedis\JWTRedisServiceProvider'

配置

完成所有操作后,请记住将此Trait添加到您的用户模型中,如果您打算与 spatie/laravel-permission 一起使用。

use JWTRedisHasRoles;

完成所有操作后,请记住将此Trait添加到您的用户模型中,如果您不使用 laravel-permission

use JWTRedis;

您需要在 app/Http/Kernel.php 中添加 $routeMiddleware 数组

<?php
return [
    'auth'               => \Chantouch\JWTRedis\Http\Middleware\Authenticate::class,
    'refreshable'        => \Chantouch\JWTRedis\Http\Middleware\Refreshable::class,
    'role'               => \Chantouch\JWTRedis\Http\Middleware\RoleMiddleware::class, // Optional
    'permission'         => \Chantouch\JWTRedis\Http\Middleware\PermissionMiddleware::class, // Optional
    'role_or_permission' => \Chantouch\JWTRedis\Http\Middleware\RoleOrPermissionMiddleware::class, // Optional
];

使用方法

您没有使用说明。此包仅影响后台,其功能几乎与Laravel会话身份验证相同,有一些例外。 您需要更改中间件。(以下将提到此问题) 您可以像往常一样使用Laravel的Auth外观、Php saver的JWTAuth外观以及所有 spatie/laravel-permission 包方法。

  • 使用令牌进行用户身份验证;
    (如果用户身份不重要,请使用此中间件。此中间件仅检查令牌是否有效。不向任何数据库发送查询。)
Route::get("/example", "ExampleController@example")->middleware('auth');
  • 为了检查用户权限,您需要使用以下中间件之一;
    (如果用户的身份很重要,请使用此中间件。此中间件从Redis获取用户并将其标记为授权给Laravel的Request对象。您可以访问所有想要的默认Auth facade方法。只需调用Laravel的Auth facade即可。)
Route::get("/example", "ExampleController@example")->middleware('role:admin|user');
Route::get("/example", "ExampleController@example")->middleware('permissions:get-user|set-user');
Route::get("/example", "ExampleController@example")->middleware('role_or_permission:admin|get-user');
  • 要刷新令牌,您可以将refreshable中间件添加到所需的路由。您不需要对此路由的控制器采取任何操作;
    (如果需要,此中间件还可以从Redis刷新用户。)
Route::get("/example", "ExampleController@example")->middleware('refreshable');

如果您想做不同的事情,可以覆盖那些提到的中间件。

按照上述方式使用后,您在应用程序中进行的所有权限检查,例如Auth::user()$user->can('permission'),都将始终从Redis检查,而不是从数据库检查。

选项

您可以在该包中自定义一些选项。请检查config/jwt-redis.php文件。

  • 用户模型
<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Your User Model
    |--------------------------------------------------------------------------
    |
    | You can set specific user model.
    |
    */
    'user_model' => \App\Models\User::class,
];
  • 观察者
<?php
return [
     /*
     |--------------------------------------------------------------------------
     | JWTRedis User Model Observer
     |--------------------------------------------------------------------------
     |
     | This observer class, listening to all events on your user model. Is triggered
     | when you assign roles & permissions to user, or update and delete to
     | your user model.
     |
     */
    'observer' => Chantouch\JWTRedis\Observers\UserRedisObserver::class,
];
  • 事件队列
<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Observer Events Are Queued
    |--------------------------------------------------------------------------
    |
    | If this option is true, model's events are processed as a job on queue.
    |
    | * ~ Remember to run Queue Worker if this option is true. ~ *
    |
    */
    'observer_events_queue' => true,
];
  • 缓存时间
<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Cache on Redis up to jwt_ttl value.
    |--------------------------------------------------------------------------
    |
    | If it's option is true, user stored in Redis up to jwt_ttl value time.
    |
    */
    'redis_ttl_jwt' => true,

    /*
    |--------------------------------------------------------------------------
    | Cache on Redis up to specific time
    |--------------------------------------------------------------------------
    |
    | If you don't want to store user in Redis until JWT expire time, 
    | you can set this value as minute.
    |
    */
    'redis_ttl' => 60,
];
  • 缓存前缀
<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Cache Prefix
    |--------------------------------------------------------------------------
    |
    | If it's user id is 1, this user stored in Redis as auth_1.
    |
    */
    'redis_auth_prefix' => 'auth_',
];
  • 禁止用户检查
<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Banned User Checking
    |--------------------------------------------------------------------------
    |
    | If the check_banned_user option is true, that users cannot access
    | the application.
    |
    */
    'check_banned_user' => false,

    /*
    |--------------------------------------------------------------------------
    | Status Column For Banned User Checking
    |--------------------------------------------------------------------------
    |
    | You can set your specific column name of your user model.
    |
    */
    'status_column_title' => 'status',


    /*
    |--------------------------------------------------------------------------
    | Restricted statuses For Banned User Checking
    |--------------------------------------------------------------------------
    |
    | If the user has one of these statuses and trying to reach your application,
    | JWTRedis throws AccountBlockedException.
    | You can set the message (check it an error array) that will return in this
    | exception.
    |
    */
    'banned_statuses' => [
        'banned',
        'deactivate'
    ],
];
  • 关系缓存
<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Cache This Relations When a User Has Authenticated
    |--------------------------------------------------------------------------
    |
    | You can add this array to your own relations, anything you want to store
    | in Redis. We recommend caching only roles and permissions here as much as
    | possible.
    |
    */
    'cache_relations' => [
        'roles.permissions',
        'permissions'
    ],
];
  • 自定义异常
<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Customize All Exception Messages and Codes
    |--------------------------------------------------------------------------
    |
    | You can customize error code,message, title for your application.
    |
    */
    'errors' => [
       'TokenNotProvidedException' => [
           'title' => 'Your custom title',
           'message' => 'Your custom error message.',
           'code' => 99999
       ]
    ],
];

示例项目

这是一个使用laravel-jwt-redis的示例。您可以详细检查。

性能改进提示

此包默认需要predis包。

您可以通过PECL安装PhpRedis PHP扩展。扩展的安装更复杂,但对于大量使用Redis的应用程序,可能提供更好的性能。Predis是PhpRedis的纯PHP替代品,默认不需要任何额外的C扩展。

"PhpRedis比Predis快约6倍。使用二进制序列化可以减少存储数据的大小约3倍。如果Redis安装在单独的机器上,减少网络流量将是一个非常显著的速度提升。"

在我看来,在生产环境中使用PhpRedis和序列化器igbinary(它提供的Lodash包为Laravel提供了这个功能)可以获得非常好的性能。

您可以阅读这篇文章,了解PhpRedisPredis的性能比较。

许可

MIT © Sek Chantouch