PHP——AES加解密 +SIGN校驗唯一性安全性(Api)
阿新 • • 發佈:2018-12-28
在這裡插入圖片描述
sign(客戶端和服務端約定的加盟方式) 驗籤每次http請都放在header中
Header中放一些基礎的引數 比如sign , version 版本號 , app_type 客戶端型別 model:手機型別 小米 華為…
sign如何生成?
1:AES對稱加密演算法
2:sign演算法生成
2:sign的唯一性
(1)寫入靜態檔案中
(2)寫入mysql中
(3)放入redis
//sign放入快取
Cache::set($header['sign'],1,config('app.app_sign_cache_time')); //校驗sign唯一性判斷 if(Cache::get($data['sign']))//存在說明該sign已經被請求了 { return false; }
以PHP服務端為例 (TP5)
寫一個公共conmon控制器繼承於次 /* * 初始化方法 * */ protected function _initialize() { $this->checkRequestAuth(); //預設呼叫檢查 方法 比如header裡面的引數 } /* * 檢查每一次APP請求的資料是否合法 * */ public function checkRequestAuth() { //首先獲取header中的資料 $header = request()->header(); //進行校驗 //todo //sign 校驗 if(empty($header['sign'])) { throw new ApiException('簽名不存在',400); } if(!in_array($header['modeltype'],config('app.apptypes'))){//判斷APPtype是否在某一個數組裡面 throw new ApiException('該手機不能使用服務!',400); } //sign校驗 $check_res = IAuth::checkSignPass($header); if(!$check_res) { throw new ApiException('sign授權失敗',400); } //sign放入快取 Cache::set($header['sign'],1,config('app.app_sign_cache_time')); $this->headers = $header; }
/**
檢查SIGN是否正常
*/
public static function checkSignPass($data)
{
try { $str = (new Aes())->decrypt($data['sign']); }catch (\Exception $e) { throw new ApiException('sign不合法!',400); } if (empty($str)) { return false; } //xxx=xx&&aaa=aa 將這種格式的字串轉為陣列格式 parse_str($str,$arr); if(!is_array($arr))// 可加入其他的判斷 { return false; } if((time() - ceil($arr['time']/ 1000)>config('app.app_sign_time'))) //判斷時間是否過期 10妙 { return false; } //sign唯一性判斷 if(Cache::get($data['sign']))//存在說明該sign已經被請求了 { return false; } return true; }
有待提高 寫作水平 !!! 加油