二人同行 發表於 2019-6-15 12:17:00

php接口数据安全解决方案(一)

<ul>
<li>前言</li>
<li>目录介绍</li>
<li>登录鉴权图</li>
<li>接口请求安全性校验整体流程图</li>
<li>代码展示</li>
<li>演示用户登录</li>
<li>演示获取用户信息</li>
<li>文章完整代码地址</li>
<li>后记</li>
</ul>
<h2 id="前言">前言</h2>
<p>目的:</p>
<ul>
<li>1.实现前后端代码分离,分布式部署</li>
<li>2.利用token替代session实现状态保持,token是有时效性的满足退出登录,token存入redis可以解决不同服务器之间session不同步的问题,满足分布式部署</li>
<li>3.利用sign,前端按照约定的方式组合加密生成字符串来校验用户传递的参数跟后端接收的参数是否一直,保障接口数据传递的安全</li>
<li>4.利用nonce,timestamp来保障每次请求的生成sign不一致,并将sign与nonce组合存入redis,来防止api接口重放</li>
</ul>
<h2 id="目录介绍">目录介绍</h2>
<hr>
<pre><code>
├── Core
│&nbsp;&nbsp; ├── Common.php(常用的公用方法)
│&nbsp;&nbsp; ├── Controller.php (控制器基类)
│&nbsp;&nbsp; └── RedisService.php (redis操作类)
├── config.php (redis以及是否开启关闭接口校验的配置项)
├── login.php (登录获取token入口)
└── user.php(获取用户信息,执行整个接口校验流程)

</code></pre>
<h2 id="登录鉴权图">登录鉴权图</h2>
<hr>
<p><img src="https://img2018.cnblogs.com/blog/595183/201906/595183-20190614182945976-471067830.png"></p>
<h2 id="接口请求安全性校验整体流程图">接口请求安全性校验整体流程图</h2>
<hr>
<p><img src="https://img2018.cnblogs.com/blog/595183/201906/595183-20190614182707043-770306388.png"></p>
<h2 id="代码展示">代码展示</h2>
<h3 id="commonphp">common.php</h3>
<pre><code>&lt;?php
namespace Core;
/**
* @desc 公用方法
* Class Common
*/
class Common{
    /**
   * @desc 输出json数据
   * @param $data
   */
    public static function outJson($code,$msg,$data=null){
      $outData = [
            'code'=&gt;$code,
            'msg'=&gt;$msg,
      ];
      if(!empty($data)){
            $outData['data'] = $data;
      }
      echojson_encode($outData);
      die();
    }

    /***
   * @desc 创建token
   * @param $uid
   */
    public static function createToken($uid){
      $time = time();
      $rand = mt_rand(100,999);
      $token = md5($time.$rand.'jwt-token'.$uid);
      return $token;
    }

    /**
   * @desc 获取配置信息
   * @param $type 配置信息的类型,为空获取所有配置信息
   */
    public static function getConfig($type=''){
      $config = include "./config.php";
      if(empty($type)){
            return $config;
      }else{
            if(isset($config[$type])){
                return $config[$type];
            }
            return [];
      }
    }

}

</code></pre>
<h3 id="redisservicephp">RedisService.php</h3>
<pre><code>&lt;?php
namespace Core;
/*
*@desc redis类操作文件
**/
class RedisService{
    private $redis;
    protected $host;
    protected $port;
    protected $auth;
    protected $dbId=0;
    static private $_instance;
    public $error;

    /*
   *@desc 私有化构造函数防止直接实例化
   **/
    private function __construct($config){
      $this-&gt;redis    =    new \Redis();
      $this-&gt;port      =    $config['port'] ? $config['port'] : 6379;
      $this-&gt;host      =    $config['host'];
      if(isset($config['db_id'])){
            $this-&gt;dbId = $config['db_id'];
            $this-&gt;redis-&gt;connect($this-&gt;host, $this-&gt;port);
      }
      if(isset($config['auth']))
      {
            $this-&gt;redis-&gt;auth($config['auth']);
            $this-&gt;auth    =    $config['auth'];
      }
      $this-&gt;redis-&gt;select($this-&gt;dbId);
    }

    /**
   *@desc 得到实例化的对象
   ***/
    public static function getInstance($config){
      if(!self::$_instance instanceof self) {
            self::$_instance = new self($config);
      }
      return self::$_instance;

    }

    /**
   *@desc 防止克隆
   **/
    private function __clone(){}

    /*
   *@desc 设置字符串类型的值,以及失效时间
   **/
    public function set($key,$value=0,$timeout=0){
      if(empty($value)){
            $this-&gt;error = "设置键值不能够为空哦~";
            return $this-&gt;error;
      }
      $res = $this-&gt;redis-&gt;set($key,$value);
      if($timeout){
            $this-&gt;redis-&gt;expire($key,$timeout);
      }
      return $res;
    }

    /**
   *@desc 获取字符串类型的值
   **/
    public function get($key){
      return $this-&gt;redis-&gt;get($key);
    }

}

</code></pre>
<h3 id="controllerphp">Controller.php</h3>
<pre><code>&lt;?php
namespace Core;
use Core\Common;
use Core\RedisService;

/***
* @desc 控制器基类
* Class Controller
* @package Core
*/
class Controller{
    //接口中的token
    public $token;
    public $mid;
    public $redis;
    public $_config;
    public $sign;
    public $nonce;

    /**
   * @desc 初始化处理
   * 1.获取配置文件
   * 2.获取redis对象
   * 3.token校验
   * 4.校验api的合法性check_api为true校验,为false不用校验
   * 5.sign签名验证
   * 6.校验nonce,预防接口重放
   */
    public function __construct()
    {
      //1.获取配置文件
      $this-&gt;_config = Common::getConfig();
      //2.获取redis对象
      $redisConfig = $this-&gt;_config['redis'];
      $this-&gt;redis = RedisService::getInstance($redisConfig);

      //3.token校验
      $this-&gt;checkToken();
      //4.校验api的合法性check_api为true校验,为false不用校验
      if($this-&gt;_config['checkApi']){
            // 5. sign签名验证
            $this-&gt;checkSign();

            //6.校验nonce,预防接口重放
            $this-&gt;checkNonce();
      }
    }

    /**
   * @desc 校验token的有效性
   */
    privatefunction checkToken(){
      if(!isset($_POST['token'])){
            Common::outJson('10000','token不能够为空');
      }
      $this-&gt;token = $_POST['token'];
      $key = "token:".$this-&gt;token;
      $mid = $this-&gt;redis-&gt;get($key);
      if(!$mid){
            Common::outJson('10001','token已过期或不合法,请先登录系统');
      }
      $this-&gt;mid = $mid;
    }

    /**
   * @desc 校验签名
   */
    private function checkSign(){
      if(!isset($_GET['sign'])){
            Common::outJson('10002','sign校验码为空');
      }
      $this-&gt;sign = $_GET['sign'];
      $postParams = $_POST;
      $params = [];
      foreach($postParams as $k=&gt;$v) {
            $params[] = sprintf("%s%s", $k,$v);
      }
      sort($params);
      $apiSerect = $this-&gt;_config['apiSerect'];
      $str = sprintf("%s%s%s", $apiSerect, implode('', $params), $apiSerect);
      if ( md5($str) != $this-&gt;sign ) {
            Common::outJson('10004','传递的数据被篡改,请求不合法');
      }
    }

    /**
   * @desc nonce校验预防接口重放
   */
    private function checkNonce(){
      if(!isset($_POST['nonce'])){
            Common::outJson('10003','nonce为空');
      }
      $this-&gt;nonce = $_POST['nonce'];
      $nonceKey = sprintf("sign:%s:nonce:%s", $this-&gt;sign, $this-&gt;nonce);
      $nonV = $this-&gt;redis-&gt;get($nonceKey);
      if ( !empty($nonV)) {
            Common::outJson('10005','该url已经被调用过,不能够重复使用');
      } else {
            $this-&gt;redis-&gt;set($nonceKey,$this-&gt;nonce,360);
      }
    }

}
</code></pre>
<h3 id="configphp">config.php</h3>
<pre><code>&lt;?php
return [
    //redis的配置
    'redis' =&gt; [
      'host' =&gt; 'localhost',
      'port' =&gt; '6379',
      'auth' =&gt; '123456',
      'db_id' =&gt; 0,//redis的第几个数据库仓库
    ],
    //是否开启接口校验,true开启,false,关闭
    'checkApi'=&gt;true,
    //加密sign的盐值
    'apiSerect'=&gt;'test_jwt'
];
</code></pre>
<h3 id="loginphp">login.php</h3>
<pre><code>&lt;?php
/**
* @desc 自动加载类库
*/
spl_autoload_register(function($className){
    $arr = explode('\\',$className);
    include $arr.'/'.$arr.'.php';
});

use Core\Common;
use Core\RedisService;

if(!isset($_POST['username']) || !isset($_POST['pwd'])){
    Common::outJson(-1,'请输入用户名和密码');
}
$username = $_POST['username'];
$pwd = $_POST['pwd'];
if($username!='admin' || $pwd!='123456' ){
    Common::outJson(-1,'用户名或密码错误');
}
//创建token并存入redis,token对应的值为用户的id
$config = Common::getConfig('redis');
$redis = RedisService::getInstance($config);
//假设用户id为2
$uid = 2;
$token = Common::createToken($uid);
$key = "token:".$token;
$redis-&gt;set($key,$uid,3600);
$data['token'] = $token;
Common::outJson(0,'登录成功',$data);

</code></pre>
<h3 id="userphp">user.php</h3>
<pre><code>&lt;?php
/**
* @desc 自动加载类库
*/
spl_autoload_register(function($className){
    $arr = explode('\\',$className);
    include $arr.'/'.$arr.'.php';
});

use Core\Controller;
use Core\Common;
class UserController extends Controller{

    /***
   * @desc 获取用户信息
   */
    public function getUser(){
      $userInfo = [
            "id"=&gt;2,
            "name"=&gt;'巴八灵',
            "age"=&gt;30,
      ];
      if($this-&gt;mid==$_POST['mid']){
            Common::outJson(0,'成功获取用户信息',$userInfo);
      }else{
            Common::outJson(-1,'未找到该用户信息');
      }
    }
}
//获取用户信息
$user = newUserController();
$user-&gt;getUser();
</code></pre>
<h2 id="演示用户登录">演示用户登录</h2>
<hr>
<p><strong>简要描述:</strong></p>
<ul>
<li>用户登录接口</li>
</ul>
<p><strong>请求URL:</strong></p>
<ul>
<li><code>http://localhost/login.php</code></li>
</ul>
<p><strong>请求方式:</strong></p>
<ul>
<li>POST</li>
</ul>
<p><strong>参数:</strong></p>
<table>
<thead>
<tr>
<th style="text-align: left">参数名</th>
<th style="text-align: left">必选</th>
<th style="text-align: left">类型</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">username</td>
<td style="text-align: left">是</td>
<td style="text-align: left">string</td>
<td>用户名</td>
</tr>
<tr>
<td style="text-align: left">pwd</td>
<td style="text-align: left">是</td>
<td style="text-align: left">string</td>
<td>密码</td>
</tr>
</tbody>
</table>
<p><strong>返回示例</strong></p>
<pre><code>{
    "code": 0,
    "msg": "登录成功",
    "data": {
      "token": "86b58ada26a20a323f390dd5a92aec2a"
    }
}

{
    "code": -1,
    "msg": "用户名或密码错误"
}

</code></pre>
<h2 id="演示获取用户信息">演示获取用户信息</h2>
<p><strong>简要描述:</strong></p>
<ul>
<li>获取用户信息,校验整个接口安全的流程</li>
</ul>
<p><strong>请求URL:</strong></p>
<ul>
<li><code>http://localhost/user.php?sign=f39b0f2dea817dd9dbef9e6a2bf478de </code></li>
</ul>
<p><strong>请求方式:</strong></p>
<ul>
<li>POST</li>
</ul>
<p><strong>参数:</strong></p>
<table>
<thead>
<tr>
<th style="text-align: left">参数名</th>
<th style="text-align: left">必选</th>
<th style="text-align: left">类型</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: left">token</td>
<td style="text-align: left">是</td>
<td style="text-align: left">string</td>
<td>token</td>
</tr>
<tr>
<td style="text-align: left">mid</td>
<td style="text-align: left">是</td>
<td style="text-align: left">int</td>
<td>用户id</td>
</tr>
<tr>
<td style="text-align: left">nonce</td>
<td style="text-align: left">是</td>
<td style="text-align: left">string</td>
<td>防止用户重放字符串 md5加密串</td>
</tr>
<tr>
<td style="text-align: left">timestamp</td>
<td style="text-align: left">是</td>
<td style="text-align: left">int</td>
<td>当前时间戳</td>
</tr>
</tbody>
</table>
<p><strong>返回示例</strong></p>
<pre><code>{
    "code": 0,
    "msg": "成功获取用户信息",
    "data": {
      "id": 2,
      "name": "巴八灵",
      "age": 30
    }
}

{
    "code": "10005",
    "msg": "该url已经被调用过,不能够重复使用"
}

{
    "code": "10004",
    "msg": "传递的数据被篡改,请求不合法"
}
{
    "code": -1,
    "msg": "未找到该用户信息"
}
</code></pre>
<h2 id="文章完整代码地址">文章完整代码地址</h2>
<hr>
<p>点击查看源代码</p>
<h2 id="后记">后记</h2>
<hr>
<p>上面完整的实现了整个api的安全过程,包括接口token生成时效性合法性验证,接口数据传输防篡改,接口防重放实现。仅仅靠这还不能够最大限制保证接口的安全。条件满足的情况下可以使用https协议从数据底层来提高安全性,另外本实现过程token是使用redis存储,下一篇文章我们将使用第三方开发的库实现JWT的规范操作,来替代redis的使用。</p><br><br>
来源:https://www.cnblogs.com/lisqiong/p/11023701.html
頁: [1]
查看完整版本: php接口数据安全解决方案(一)