hypedev-group/jwt-redis

此包允许使用 JWT 认证的用户在 Redis 中存储和管理,包括其角色、权限、状态等您需要的内容。

dev-master 2023-11-21 12:24 UTC

This package is auto-updated.

Last update: 2024-09-21 13:58:30 UTC


README

此包允许使用 JWT 认证的用户在 Redis 中存储和管理,包括其角色、权限、状态等您需要的内容。

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

需求

此包与底层 tymondesigns/jwt-authspatie/laravel-permission 包一起工作。

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

安装

composer require hypedev-group/jwt-redis

完成此操作后,您需要将以下值添加到或更改 .env 文件中的这些值。

CACHE_DRIVER=redis
REDIS_CLIENT=predis

接下来,您需要更改 config/auth.php 配置文件中的 guardsproviders 数组,如下所示

'guards' => [
        'api' => [
            'driver' => 'jwt_redis_guard',
            'provider' => 'users'
        ],
    ],

'providers' => [
        'users' => [
            'driver' => 'jwt_redis_user_provider',
            'model' =>  App\User::class, // Your User Model
        ],
    ],

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

HypeDevGroup\JWTRedis\JWTRedisServiceProvider::class,

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

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

配置

完成所有操作后,不要忘记将此 trait 添加到您的用户模型中。

use JWTRedisHasRoles;

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

'auth'               => \HypeDevGroup\JWTRedis\Http\Middleware\Authenticate::class,
'refreshable'        => \HypeDevGroup\JWTRedis\Http\Middleware\Refreshable::class,
'role'               => \HypeDevGroup\JWTRedis\Http\Middleware\RoleMiddleware::class,
'permission'         => \HypeDevGroup\JWTRedis\Http\Middleware\PermissionMiddleware::class,
'role_or_permission' => \HypeDevGroup\JWTRedis\Http\Middleware\RoleOrPermissionMiddleware::class,

使用方法

您没有使用说明。此包仅影响后台,几乎与 Laravel 会话认证以相同的方式工作,有一些例外。 您需要做的就是更改您的中间件。(我将在下面提到这一点) 您可以使用 Laravel 的 Auth 门面、Tymon 的 JWTAuth 门面以及所有 spatie/laravel-permission 包方法,就像平常一样。

  • 对于通过令牌进行用户身份验证;
    (使用此中间件,如果用户的身份不重要。此中间件仅检查令牌是否有效。不会向任何数据库发送查询。)
    Route::get("/example", "ExampleController@example")->middleware('auth');
    
  • 要检查用户授权,您需要使用以下中间件之一;
    (使用此中间件,如果用户的身份很重要。此中间件从 Redis 中检索用户并将其标记为授权给 Laravel 的请求对象。您将能够访问所有默认的 Auth 门面方法。只需调用 Laravel 的 Auth 门面即可。)
    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/jwtredis.php 文件。

  • 用户模型
      /*
      |--------------------------------------------------------------------------
      | Your User Model
      |--------------------------------------------------------------------------
      |
      | You can set specific user model.
      |
      */
      'user_model' => \App\Models\User::class,
    
  • 观察者
       /*
       |--------------------------------------------------------------------------
       | JWTRedis User Model Observer
       |--------------------------------------------------------------------------
       |
       | This observer class, listening all events on your user model. Is triggered
       | when you assign roles & permissions to user, or update and delete to
       | your user model.
       |
       */
      'observer' => \HypeDevGroup\JWTRedis\Observers\UserRedisObserver::class,
    
  • 事件队列
      /*
      |--------------------------------------------------------------------------
      | Observer Events Are Queued
      |--------------------------------------------------------------------------
      |
      | If this option is true, model's events are processed as a job on queue.
      | The job will be executed after the database transactions are commit.
      |
      | * ~ Don't forget to run Queue Worker if this option is true. ~ *
      |
      */
      'observer_events_queue' => env('JWTREDIS_OBSERVER_EVENTS_QUEUE', false),
    
  • 缓存时间

      /*
      |--------------------------------------------------------------------------
      | 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' => env('JWTREDIS_REDIS_TTL', 60),
    
  • 缓存前缀
      /*
      |--------------------------------------------------------------------------
      | Cache Prefix
      |--------------------------------------------------------------------------
      |
      | If it's user id is 1, this user stored in Redis as auth_1.
      |
      */
      'redis_auth_prefix' => env('JWTREDIS_REDIS_AUTH_PREFIX', 'auth_'),
    
  • 序列化
      /*
     |--------------------------------------------------------------------------
     | Igbinary Serialization
     |--------------------------------------------------------------------------
     |
     | Igbinary Serialization provides a better performance and lower memory 
     | usage than PHP Serialization.
     |
     | * ~ Don't forget to enable igbinary extension if this option is true. ~ *
     |
     */
      'igbinary_serialization' => env('JWTREDIS_IGBINARY_SERIALIZATION', false),
    
  • 禁止用户检查

      /*
      |--------------------------------------------------------------------------
      | Banned User Checking
      |--------------------------------------------------------------------------
      |
      | If the check_banned_user option is true, that users cannot access
      | the your application.
      |
      */
      'check_banned_user' => env('JWTREDIS_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 errors array) that will return in this
| exception.
|
*/
'banned_statuses' => [
    'banned',
    'deactivate'
],
* Relation Caching
/*
|--------------------------------------------------------------------------
| Cache This Relations When 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'
],
* Customize Exceptions
/*
|--------------------------------------------------------------------------
| 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
   ]
]

## Example Project
Here is an [example](https://github.com/HypeDevGroup/laravel-jwtredis-example) using laravel-jwtredis. You can examine in detail.

## Performance Improvements Tips

You may install the PhpRedis PHP extension via PECL. The extension is more complex to install but may yield better performance for applications that make heavy use of Redis. Predis is the alternative for PhpRedis on pure PHP and does not require any additional C extension by default.

"PhpRedis is faster about x6 times. Using igbinary serializer reduces stored data size about 3x times. If Redis installed on separate machines, reducing network traffic is a very significant speedup."

In my opinion, using [PhpRedis](https://github.com/phpredis/phpredis) and serializer as igbinary ( Laravel does not support igbinary serialization on Redis. However, this package provides igbinary serialization support for Laravel. Please check `config/jwtredis.php` file. ) in production environment gives a great performance.

You can review this  [article](https://medium.com/@akalongman/phpredis-vs-predis-comparison-on-real-production-data-a819b48cbadb) for performance comparison [PhpRedis](https://github.com/phpredis/phpredis) vs. [Predis](https://github.com/nrk/predis).

## Integrate with [Laravel Swoole Package](https://github.com/swooletw/laravel-swoole)
This package fully compatible with  [Laravel Swoole](https://github.com/swooletw/laravel-swoole) package. If you want to use it together, all you have to do is change the `instances` and `providers` arrays in your `config/swoole_http.php` config as follows:

/*
|--------------------------------------------------------------------------
| Instances here will be cleared on every request.
|--------------------------------------------------------------------------
*/
'instances' => [
    'auth'
],

/*
|--------------------------------------------------------------------------
| Providers here will be registered on every request.
|--------------------------------------------------------------------------
*/
'providers' => [
    \HypeDevGroup\JWTRedis\JWTRedisServiceProvider::class,
],