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);
    }
}
相關文章
相關標籤/搜索