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


Posted in PHP onSeptember 30, 2019

背景

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

调研

config/auth.php文件中发现用户的驱动使用的是EloquentUserProvider服务提供器,然后查找EloquentUserProvider.php 然后发现在vendor/laravel/framework/src/Illuminate/Auth文件下存在该文件

<?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类,重写

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文件下修改如下代码

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。

后续

改完代码以后发现无法正常登录,一直提示用户或密码错误。。。然后看看了下用户认证方法是

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);
 }
}

然后登录成功啦!皆大欢喜!

以上这篇Laravel的Auth验证Token验证使用自定义Redis的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
PHP初学者头疼问题总结
Jul 08 PHP
vBulletin Forum 2.3.xx SQL Injection
Oct 09 PHP
如何利用php+mysql保存和输出文件
Oct 09 PHP
教你如何把一篇文章按要求分段
Oct 09 PHP
一些PHP写的小东西
Dec 06 PHP
PHP Directory 函数的详解
Mar 07 PHP
php的数组与字符串的转换函数整理汇总
Jul 18 PHP
PHP中is_file不能替代file_exists的理由
Mar 04 PHP
php foreach正序倒序输出示例代码
Jul 01 PHP
PHP连接和操作MySQL数据库基础教程
Sep 29 PHP
WordPress中Gravatar头像缓存到本地及相关优化的技巧
Dec 19 PHP
PHP获取文件扩展名的常用方法小结【五种方式】
Apr 27 PHP
Laravel框架控制器的middleware中间件用法分析
Sep 30 #PHP
Laravel 已登陆用户再次查看登陆页面的自动跳转设置方法
Sep 30 #PHP
laravel实现登录时监听事件,添加登录用户的记录方法
Sep 30 #PHP
php7下的filesize函数
Sep 30 #PHP
laravel利用中间件防止未登录用户直接访问后台的方法
Sep 30 #PHP
laravel实现Auth认证,登录、注册后的页面回跳方法
Sep 30 #PHP
Laravel框架表单验证操作实例分析
Sep 30 #PHP
You might like
PHP 根据IP地址控制访问的代码
2010/04/22 PHP
简洁短小的 JavaScript IE 浏览器判定代码
2010/03/21 Javascript
理解Javascript_14_函数形式参数与arguments
2010/10/20 Javascript
jquery导航制件jquery鼠标经过变色效果示例
2013/12/05 Javascript
15个jquery常用方法、小技巧分享
2015/01/13 Javascript
JS插件overlib用法实例详解
2015/12/26 Javascript
Vue2.0表单校验组件vee-validate的使用详解
2017/05/02 Javascript
详细分析JS函数去抖和节流
2017/12/05 Javascript
JavaScript数据结构与算法之二叉树插入节点、生成二叉树示例
2019/02/21 Javascript
vue自定义指令实现仅支持输入数字和浮点型的示例
2019/10/30 Javascript
js实现抽奖功能
2020/11/24 Javascript
在vue项目中封装echarts的步骤
2020/12/25 Vue.js
Python获取DLL和EXE文件版本号的方法
2015/03/10 Python
以一个投票程序的实例来讲解Python的Django框架使用
2016/02/18 Python
Python实现简单的四则运算计算器
2016/11/02 Python
Python yield 使用方法浅析
2017/05/20 Python
tensorflow实现加载mnist数据集
2018/09/08 Python
python的pytest框架之命令行参数详解(上)
2019/06/27 Python
Python替换月份为英文缩写的实现方法
2019/07/15 Python
Python缓存技术实现过程详解
2019/09/25 Python
Python3 操作 MySQL 插入一条数据并返回主键 id的实例
2020/03/02 Python
python实现密码验证合格程序的思路详解
2020/06/01 Python
Python命令行参数argv和argparse该如何使用
2021/02/08 Python
canvas学习笔记之2d画布基础的实现
2019/02/21 HTML / CSS
台湾生鲜宅配:大口市集
2017/10/14 全球购物
香港通票:Hong Kong Pass
2019/02/26 全球购物
Belstaff英国官方在线商店:Belstaff.co.uk
2021/02/09 全球购物
CSMA/CD介质访问控制协议
2015/11/17 面试题
LINUX下线程,GDI类的解释
2016/12/14 面试题
成人大专自我鉴定范文
2013/10/19 职场文书
优秀学生干部推荐材料
2014/02/03 职场文书
代办委托书怎样写
2014/04/08 职场文书
部门2015年度工作总结
2015/04/29 职场文书
关于办理居住证的介绍信模板
2019/11/27 职场文书
python字典的元素访问实例详解
2021/07/21 Python
剖析后OpLog订阅MongoDB的数据变更就没那么难了
2022/02/24 MongoDB