淺談API開發安全之sign校驗(二)

前面我們說了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類就可以啦 ,當然,還有一些細節需要我們處理
如需瞭解更多,可以查看下一篇文章,將講解如何定義sign有效時間淺談API開發安全之sign有效時間(三)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章