Laravel的Auth验证Token验证自定义使用Redis

  • 背景

项目用户量逐渐增大,接口调用次数愈来愈多,因此决定使用Redis存token,缓解数据库压力php

  • 调研

我用的的laravel是5.2版本。在config/auth.php文件中发现用户的驱动使用的是eloquent,而后查找EloquentUserProvider.php 而后发如今vendor/laravel/framework/src/Illuminate/Auth文件下存在该文件html

<?php
 
namespace Illuminate\Auth;
 
use Illuminate\Support\Str;
use Illuminate\Contracts\Auth\UserProvider;
use Illuminate\Contracts\Hashing\Hasher as HasherContract;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
 
class EloquentUserProvider implements UserProvider
{
    /**
     * The hasher implementation.
     *
     * @var \Illuminate\Contracts\Hashing\Hasher
     */
    protected $hasher;
 
    /**
     * The Eloquent user model.
     *
     * @var string
     */
    protected $model;
 
    /**
     * Create a new database user provider.
     *
     * @param  \Illuminate\Contracts\Hashing\Hasher  $hasher
     * @param  string  $model
     * @return void
     */
    public function __construct(HasherContract $hasher, $model)
    {
        $this->model = $model;
        $this->hasher = $hasher;
    }
 
    /**
     * Retrieve a user by their unique identifier.
     *
     * @param  mixed  $identifier
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveById($identifier)
    {
        return $this->createModel()->newQuery()->find($identifier);
    }
    ...
     /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
        if (empty($credentials)) {
            return;
        }
 
        // First we will add each credential element to the query as a where clause.
        // Then we can execute the query and, if we found a user, return it in a
        // Eloquent User "model" that will be utilized by the Guard instances.
        $query = $this->createModel()->newQuery();
 
        foreach ($credentials as $key => $value) {
            if (! Str::contains($key, 'password')) {
                $query->where($key, $value);
            }
        }
 
        return $query->first();
    }
...
}

  

  • 实现代码

由于咱们是须要在当前的Auth验证基础之上添加一层Redis缓存,因此最简单的办法继承EloquentUserProvider类,重写laravel



retrieveByCredentials方法因此咱们新建RedisUserProvider.php文件
<?php
namespace App\Providers;
 
use Illuminate\Auth\EloquentUserProvider;
use Cache;
 
class RedisUserProvider extends EloquentUserProvider
{
 
    public function __construct($hasher, $model)
    {
        parent::__construct($hasher, $model);
    }
    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
 
        if (!isset($credentials['token'])) {
            return;
        }
 
        $token = $credentials['token'];
        $redis = Cache::getRedis();
        $userId = $redis->get($token);
       
        return $this->retrieveById($userId);
    }
}

  而后在AuthServiceProvider.php文件下修改以下代码web

  public function boot(GateContract $gate)
    {
        $this->registerPolicies($gate);
 
        //将redis注入Auth中
        Auth::provider('redis',function($app, $config){
            return new RedisUserProvider($app['hash'], $config['model']);
        });
    }

  

修改config/auth.php用户的auth的驱动为redis。redis

  • 后续

改完代码之后发现没法正常登陆,一直提示用户或密码错误。。。而后看看了下用户认证方法是数据库

auth('web')->once($credentials);而后看是在
Illuminate\Auth\SessionGuard文件中用到了RedisUserProvider文件中retrieveByCredentials方法中对用户进行密码验证,因而修改RedisUserProvider文件缓存

<?php
namespace App\Providers;
 
use Illuminate\Auth\EloquentUserProvider;
use Illuminate\Support\Str;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Cache;
 
class RedisUserProvider extends EloquentUserProvider
{
 
    public function __construct($hasher, $model)
    {
        parent::__construct($hasher, $model);
    }
    /**
     * Retrieve a user by the given credentials.
     *
     * @param  array  $credentials
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
     */
    public function retrieveByCredentials(array $credentials)
    {
 
        if (empty($credentials)) {
            return;
        }
        if(isset($credentials['phone']) && isset($credentials['password'])){
            // First we will add each credential element to the query as a where clause.
            // Then we can execute the query and, if we found a user, return it in a
            // Eloquent User "model" that will be utilized by the Guard instances.
            $query = $this->createModel()->newQuery();
 
            foreach ($credentials as $key => $value) {
                if (! Str::contains($key, 'password')) {
                    $query->where($key, $value);
                }
            }
 
            return $query->first();
        }
 
        $token = $credentials['token'];
        $redis = Cache::getRedis();
        $userId = $redis->get($token);
 
        return $this->retrieveById($userId);
    }
}
相关文章
相关标签/搜索