
上一章 我们说了 sign的生成 那么 我们如何确定这个sign的准确性呢 下来 我们说说 校验sign的那些事
在拿到header里面的内容之后 我们首先需要对其内容的基本参数做一个校验 我们补充下Common类的代码
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/8/15
* Time: 15:00
*/ namespace app\index\controller; use app\common\lib\execption\ApiException;
use think\Controller; class Common extends Controller
{
public function _initialize(){
$this->checkRequestAuth();
} public function checkRequestAuth(){
$header = request()->header(); ##判断header中基础参数
if(empty($header['sign'])){
throw new ApiException('sign不存在',400);
}
if(!in_array($header['app_type'],config("app.app_types"))){
throw new ApiException('app_type不合法',400);
}
}
}
判定基础参数之后 我们就要进入正题了 校验sign 那么在鉴权类 IAuth 里面新增 checkSignPass 方法 校验sign
/**
* 校验SIGN是否正常
* @param $data
*/
public static function checkSignPass($data){
##解密
$str = (new Aes())->decrypt($data['sign']); if(empty($str)){
return false;
}
##转换为数组
parse_str($str,$arr);
##判定条件根据需求可增加
if(!is_array($arr) || empty($arr['did']) || $arr['did'] != $data['did']){
return false;
}
return true;
}
方法添加完成后 我们需要在Common里面进行校验
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/8/15
* Time: 15:00
*/ namespace app\index\controller; use app\common\lib\execption\ApiException;
use app\common\lib\IAuth;
use think\Controller; class Common extends Controller
{
public $header = ''; public function _initialize(){
$this->checkRequestAuth();
} public function checkRequestAuth(){
$header = request()->header(); ##判断header中基础参数
if(empty($header['sign'])){
throw new ApiException('sign不存在',400);
} if(!in_array($header['apptype'],config("app.app_types"))){
throw new ApiException('app_type不合法',400);
}
##调用鉴权类校验sign的准确性
if(!IAuth::checkSignPass($header)){
throw new ApiException('授权码sign失败',401);
}
##如果校验通过 将header值存起来 方便后面使用
$this->header = $header;
}
}
到这里 sign基本就校验完毕 后面只需要业务逻辑类 继承Common类就可以啦 当然 还有一些细节需要我们处理 下一章 我们再来进行