情诗网 >高端情话 > 正文

[PHP高可用后端]②⑤--sign校验

来源:情诗网    2020-11-07    分类:高端情话

image.png

app.php

<?php
/**
 * Created by PhpStorm.
 * User: tong
 * Date: 2017/11/20
 * Time: 11:43
 */
return [
    'password_pre_halt' => '_#sing_ty',//密码加密言
    'aeskey' => 'sgg45747ss223455',//aes密钥,服务端和客户端必须保持一致
    'apptypes'=>[
        'ios',
        'android',
    ],
];

IAuth.php

<?php
/**
 * Created by PhpStorm.
 * User: tong
 * Date: 2017/11/20
 * Time: 13:56
 */

namespace app\common\lib;

class IAuth
{

    public static function setPassword($data)
    {
        return md5($data . config('app.password_pre_halt'));
    }

    public static function setSign($data = [])
    {
        ksort($data);
        $string = http_build_query($data);
        $string = (new Aes())->encryt($string);
        return $string;
    }

    /**
     * 检查sign是否正常
     * @param string $sign
     * @param $data
     * @return boolean
     */
    public static function checkSignPass($data)
    {
        $str = (new Aes())->decrypt($data['sign']);
        if (empty($str)) {
            return false;
        }
        //diid=xx&app_type=3
        parse_str($str, $arr);

        /**
         * array (size=2)
         * 'did' => string '12345dg' (length=7)
         * 'version' => string '1' (length=1)
         */
        //halt($arr);

        if (!is_array($arr) || empty($arr['did'])
            || $arr['did'] != $data['did']
        ) {
            return false;
        }
        return true;
    }
}

Common.php

<?php
/**
 * Created by PhpStorm.
 * User: tong
 * Date: 2017/11/21
 * Time: 14:26
 */

namespace app\api\controller;

use app\common\lib\Aes;
use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;
use think\Controller;

class Common extends Controller
{
    /**
     * @var string
     */
    public $headers='';


    protected function _initialize()
    {
        $this->checkRequestAuth();
    }

    public function checkRequestAuth()
    {
        $headers = request()->header();
        //$this->testAes();

        //sign加密需要客户端工程师 解密 服务端工程师

        //基础检验
        if (empty($headers['sign'])) {
            throw new ApiException('sign不存在', 400);
        }
        if (!in_array($headers['app_type'], config('app.apptypes'))) {
            throw new ApiException('app_type不合法', 400);
        }

        if (!IAuth::checkSignPass($headers)) {
           throw new ApiException('授权码sign失败',401);
        }

        $this->headers=$headers;




    }

    public function testAes()
    {
        $data = [
            'did' => '12345dg',
            'version' => 1,
        ];
        $str = ' ';
        echo (new Aes())->decrypt($str);
        exit;
    }
}
image.png

热门文章