上一章 我們說了 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類就可以啦 當然 還有一些細節需要我們處理 下一章 我們再來進行
