服务端API安全解决方案

由于server端和client端需要通信,所以api的安全性需要保证

1.完全开放的

一般只是查询,不能执行增、删、改的操作

裸奔的

<?php
public function getGoodsList($params)
{
    $where = [
       'cat_id'=>$params['cat_id']
    ];
    $goods = M('Goods')->where($where)->select();
    return json_encode($goods);
}

 

2.参数加密

参数按照规则生成sign

<?php
public function getUserInfo($params, $appKey, $sign)
{$currentSign = $this->getSign($appKey, $params);
    if($sign !== $currentSign) {
        return "签名不合法";
    }
    $where = ['id'=>$params['id']];
    $user = M('User')->where($where)->select();
    return json_encode($user);
}

 

3.参数加密+时效性验证

<?php

public function getUserInfo($params, $appKey, $sign, $timestamp)
{
    //判断请求是否过期---假设过期时间是20秒
    $request_time = getDateTimeByTicks($timestamp);
    if(($request_time + 20) < $_SERVER["REQUEST_TIME"]) {
        return "接口过期";
    }
    
    $currentSign = $this->getSign($appKey, $params);

    if($sign !== $currentSign) {
        return "签名不合法";
    }
    
    $where = [
       'id'=>$params['id']
    ];
    $user = M('User')->where($where)->select();
    return json_encode($user);
}
 

 

4.参数加密+时效性验证+私钥

<?php
public function updateUserInfo($params, $appKey, $sign, $timestamp)
{

    $requestTime = getDateTimeByTicks($timestamp);
    if(($requestTime + 20) < $_SERVER["REQUEST_TIME"]) {
        return "接口过期";
    }

    // 根据appkey查库获取appSecret值
    $appSecret = M('Setting')->where(['appKey'=> $appKey])->getField('appSecret');
    
    //检验签名是否合法
    $currentSign = $this->getSign($appKey, $appSecret, $params);

    if($sign !== $currentSign) {
        return "签名不合法";
    }
    
    $where = ['id'=>$params['id']];
    unset($params['id']);
    $data = M('User')->where($where)->save($params);
    return json_encode($data);
}

5.参数加密+时效性验证+私钥+Https

为了提高安全性,再增加https的双向验证模式

生成签名的方法:

  (1)对除签名外的所有请求参数按key做生序排列   

     如:age=18,name=123,timestamp=123456

  (2)把参数名和参数值连接成字符串 
     如:age18_name123_timestamp123456

  (3)用申请到的appkey连接到拼装字符串头部和尾部,然后进行32位MD5加密,将到得MD5加密摘要转化成大写

    如:appkey='bb',md5('bbage18_name123_timestamp123456bb')

      sign='3FFDD2399A23FB7B5D6D99AA84F9A6E3'

 

posted @ 2018-11-23 14:43  慕尘  阅读(247)  评论(0编辑  收藏  举报