api接口设计 | laravel china 社区-江南app体育官方入口

首先接口是不能裸奔的,不然你就boom了!!!
首先接口是不能裸奔的,不然你就boom了!!!
首先接口是不能裸奔的,不然你就boom了!!!

一、那么接口一般面临三个安全问题

  1. 请求身份是否合法
  2. 请求参数是否被篡改
  3. 请求是否唯一(重放攻击)

二、那么针对这三个问题,怎么解决呢??

  1. 请求身份合法问题就用接口签名认证(sign)解决,需要登录才能操作的api还要验证用户的token
  2. 请求参数篡改的问题就对入参除sign外的其他参数的key升序或者降序,再拼上api的加密密钥secretkey=,然后用一个不可逆的加密算法,例如md5,这样就能得出sign
  3. 请求的唯一问题就定义api必须传ts(时间戳)和nonce(随机唯一code)这两个参数,后端将nonce作为key用redis存起来,给一个过期时间,只要是在过期内重复请求就拦截

这样下来,三个问题就能解决了,这是常规的接口认证方式!!!

三、接下来就是coding time

首先我这里图个方便,api响应用了组件

composer require sevming/laravel-response:^1.0

涉及到接口拦截响应msg,code还有用到得缓存key这些建议都用枚举(enum)存放,还有api一般都有v1、v2…等不同版本,所以要做好目录结构。

这是存放api拦截响应信息的枚举类


namespace app\http\enums\api\v1;
class apiresponseenum
{
    const defect_sign = '缺失sign签名|10001';
    const defect_timestamp = '缺失ts时间戳|10002';
    const defect_nonce = '缺失nonce|10003';
    const invalid_sign = '非法sign签名|20001';
    const invalid_timestamp = '非法ts时间戳|20002';
    const invalid_nonce = '非法请求|20003';
    const defect_token = '缺失token|30001';
    const invalid_token = '非法token|30002';
    const twice_password_not_same = '两次密码不一致|40001';
    const account_has_register = '账号已注册|40002';
    const invalid_email_format = '邮箱格式不对|40003';
    const invalid_password_length = '密码至少8位|40004';
    const wei_code_has_register = '微聊号已注册|40005';
    const register_error = '注册失败|40006';
    const account_not_exists = '账号不存在|40007';
    const account_has_ban = '账号已被封禁|40008';
    const invalid_password = '密码错误|40009';
}

还有一个存放缓存key的


namespace app\http\enums\api\v1;
//api 缓存key 枚举类
class apicachekeyenum
{
    const nonce_cache_key = 'api_request_nonce:';
    const token_cache_key = 'user_token:';
}

关于api认证的设计

设计思想:首先在api的基类中统一对接口入参做一个入参检测,也就是配置必传参数、设置默认值等,这样就不用在业务层中对参数做繁琐的判空处理。然后api认证及token校验的拦截用中间件去做。

  1. 首先建一个api的配置文件(api.php),读.env里的配置,这里的params_check就是配置接口入参检测的,凡是配置的参数都是必传的,key是接口方法名(取决于路由,本人一般路由与接口方法名会保持一致)。这里不用表单验证器是因为本人觉得每个接口方法都要写一个表单验证实在繁琐,所以改成了这种配置的方式。

use app\http\controllers\api\baseapi;
return [
    'v1' => [
        'api_key' => env('api_key_v1'),//api sign加密密钥
        'user_key' => env('user_key_v1'),//用户token加密密钥,
        //接口入参检测
        'params_check' => [
            '_register' => [
                'name' => [
                    'type' => baseapi::param_string,//入参类型
                    'default' => 'user' . uniqid()//默认值
                ],
                'email' => baseapi::param_string,
                'password' => baseapi::param_string,
                'confirm_password' => baseapi::param_string
            ],
            '_login' => [
                'email' => baseapi::param_string,
                'password' => baseapi::param_string
            ]
        ]
    ],
];
  1. api基类的实现(baseapi)

namespace app\http\controllers\api;
use app\http\enums\api\v1\apicachekeyenum;
use sevming\laravelresponse\support\facades\response;
use illuminate\support\facades\redis;
class baseapi
{
    const param_int = 1;//整型
    const param_string = 2;//字符串
    const param_array = 3;//数组
    const param_file = 4;//文件
    protected $params;
    public function __construct()
    {
        //入参检测,并初始化入参
        $this->params = $this->check_params();
    }
    //api接口统一入参检测
    public function check_params()
    {
        $action_list = explode('/', \request()->path());
        $params_check_key = end($action_list);
        //入参检测配置
        $params_check = config('api.v1.params_check.' . $params_check_key);
        //入参
        $params = request()->input();
        if (is_array($params_check) && $params_check) {
            $flag = true;
            foreach ($params_check as $key => $check) {
                if (is_array($check)) {
                    $type = $check['type'] ?? 2;//默认是字符串
                    $default = $check['default'] ?? '';//默认值
                } else {
                    $type = $check;
                }
                if (array_key_exists($key, $params)) {
                    switch ($type) {
                        case self::param_int:
                            $flag = is_numeric($params[$key]) || (isset($default) && empty($params[$key]));
                            break;
                        case self::param_string:
                            $flag = is_string($params[$key]) || (isset($default) && empty($params[$key]));
                            break;
                        case self::param_array:
                            $flag = is_array($params[$key]) || (isset($default) && empty($params[$key]));
                            break;
                        case self::param_file:
                            $flag = $_files[$key] && isset($_files[$key]['error']) && $_files[$key]['error'] == 0;
                            break;
                    }
                } else {
                    $flag = false;
                }
                if (!$flag) {
                    return response::fail('invalid param ' . $key);
                }
                //默认值处理
                if (empty($params[$key]) && isset($default)) {
                    $params[$key] = $default;
                }
                //文件处理
                if ($type === baseapi::param_file) {
                    $params[$key] = $_files[$key];
                }
                unset($default);
            }
        }
        //根据token获取uid
        if (array_key_exists('token', $params)) {
            //获取uid
            $redis = redis::connection();
            $uid = $redis->get(apicachekeyenum::token_cache_key . $params['token']);
            $params['uid'] = $uid ?? 0;
            unset($params['token']);
        }
        unset($params['sign']);
        return $params;
    }
}
  1. 用到的一些公共函数放到common.php中,这个看习惯

//公共函数
if (!function_exists('make_sign')) {
    //生成签名
    function make_sign($params)
    {
        unset($params['sign']);
        $params['api_key'] = config('api.v1.api_key');//拼接api加密密钥
        ksort($params);//key升序
        $string_temp = http_build_query($params);
        return md5($string_temp);
    }
}
if (!function_exists('encrypt_token')) {
    //生成token
    function encrypt_token($uid)
    {
        $user_info = [
            'uid' => $uid,
            'ts' => time()
        ];
        $user_key = config('api.v1.user_key');
        return openssl_encrypt(base64_encode(json_encode($user_info)), 'des-ecb', $user_key, 0);
    }
}
if (!function_exists('make_avatar')) {
    function make_avatar($email)
    {
        $md5_email = md5($email);
        return "https://api.multiavatar.com/{$md5_email}.png";
    }
}
  1. api服务类实现接口的签名认证和token校验方法

namespace app\http\contracts\api\v1;
interface apiinterface
{
    //api签名认证
    public function checksign($params);
    //用户token校验
    public function checktoken($params);
}

namespace app\http\services\api\v1;
use app\http\contracts\api\v1\apiinterface;
use app\http\enums\api\v1\apicachekeyenum;
use app\http\enums\api\v1\apiresponseenum;
use illuminate\support\facades\redis;
use sevming\laravelresponse\support\facades\response;
class apiservice implements apiinterface
{
    public static $instance = null;
    /**
     * @return static|null
     * 单例模式
     */
    public static function getinstance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new static();
        }
        return self::$instance;
    }
    /**
     * @param $params array 入参
     * 签名认证
     */
    public function checksign($params)
    {
        // todo: implement checksign() method.
        if (!isset($params['sign'])) {
            return response::fail(apiresponseenum::defect_sign);
        }
        if (!isset($params['ts'])) {
            return response::fail(apiresponseenum::defect_timestamp);
        }
        if (!isset($params['nonce'])) {
            return response::fail(apiresponseenum::defect_nonce);
        }
        $ts = $params['ts'];//时间戳
        $nonce = $params['nonce'];
        $sign = $params['sign'];
        $time = time();
        if ($ts > $time) {
            return response::fail(apiresponseenum::invalid_timestamp);
        }
        $redis = redis::connection();
        if ($redis->exists(apicachekeyenum::nonce_cache_key . $nonce)) {
            return response::fail(apiresponseenum::invalid_nonce);
        }
        $api_sign = make_sign($params);
        if ($api_sign !== $sign) {
            return response::fail(apiresponseenum::invalid_sign);
        }
        //5分钟内一个sign不能重复请求,防止重放攻击
        $redis->setex(apicachekeyenum::nonce_cache_key . $nonce, 300, $time);
        return true;
    }
    /**
     * @param $params
     * token校验
     */
    public function checktoken($params)
    {
        // todo: implement checktoken() method.
        $action_list = explode('/', \request()->path());
        $action = end($action_list);
        //带下划线的方法无需登录,直接放行
        if (stripos($action, '_')) {
            return true;
        }
        if (!isset($params['token'])) {
            return response::fail(apiresponseenum::defect_token);
        }
        $token = $params['token'];
        //查缓存是否存在该登录用户token
        $redis = redis::connection();
        $cache_token = $redis->get(apicachekeyenum::token_cache_key . $token);
        if (!$cache_token) {
            return response::fail(apiresponseenum::invalid_token);
        }
        return true;
    }
}
  1. api认证拦截的中间件

namespace app\http\middleware;
use app\http\services\api\v1\apiservice;
use closure;
class apiintercept
{
    public function handle($request, closure $next)
    {
        $params = $request->input();
        $env = config('env');
        if ($env !== 'local') {
            //非本地环境,需要签名认证
            apiservice::getinstance()->checksign($params);
        }
        //token检验
        apiservice::getinstance()->checktoken($params);
        return $next($request);
    }
}


四、下面以简单的登录注册为例子

  1. user模型类

/**
 * user: yanjianfei
 * date: 2021/9/18
 * time: 10:17
 */
namespace app\model;
use app\http\enums\api\v1\apicachekeyenum;
use app\http\enums\api\v1\apiresponseenum;
use illuminate\support\facades\redis;
use sevming\laravelresponse\support\facades\response;
class user extends basemodel
{
    //注册
    public function checkregister($params)
    {
        if ($params['password'] !== $params['confirm_password']) {
            return response::fail(apiresponseenum::twice_password_not_same);
        }
        if (strlen($params['password']) < 8) {
            return response::fail(apiresponseenum::invalid_password_length);
        }
        $pattern = '^\w ([- .]\w )*@\w ([-.]\w )*\.\w ([-.]\w )*$';
        if (preg_match($pattern, $params['email'])) {
            return response::fail(apiresponseenum::invalid_email_format);
        }
        $account_exits = self::query()->where('email', $params['email'])->exists();
        if ($account_exits) {
            return response::fail(apiresponseenum::account_has_register);
        }
        $wei_code_exists = self::query()->where('wei_code', $params['wei_code'])->exists();
        if ($wei_code_exists) {
            return response::fail(apiresponseenum::wei_code_has_register);
        }
        $data = [
            'name' => $params['name'],
            'password' => md5($params['password']),
            'avatar' => make_avatar($params['email']),
            'email' => $params['email']
        ];
        $user = self::query()->create($data);
        if (!$user) {
            return response::fail();
        }
        //注册完后自动登录
        return $this->checklogin($user, true);
    }
    /**
     * @param $params
     * @param false $auto 自动登录
     */
    public function checklogin($params, $auto = false)
    {
        $user = $params;
        if (!$auto) {
            $user = self::query()->where('email', $params['email'])->first();
            if (!$user) {
                return response::fail(apiresponseenum::account_not_exists);
            }
            if ($user['status'] == 0) {
                return response::fail(apiresponseenum::account_has_ban);
            }
            if ($user['password'] !== md5($params['password'])) {
                return response::fail(apiresponseenum::invalid_password);
            }
        }
        $token = encrypt_token($user['id']);//生成token
        $redis = redis::connection();
        $redis->setex(apicachekeyenum::token_cache_key . $token, 86400, $user['id']);//reids存放token
        return [
            'token' => $token,
            'name' => $user['name'],
            'avatar' => $user['avatar']
        ];//返回登录信息
    }
}
  1. user控制器

/**
 * user: yanjianfei
 * date: 2021/9/17
 * time: 17:01
 */
namespace app\http\controllers\api\v1;
use app\http\controllers\api\baseapi;
use sevming\laravelresponse\support\facades\response;
use app\model\user as usermodel;
class user extends baseapi
{
    public function _login(usermodel $user)
    {
        $data = $user->checklogin($this->params);
        return response::success($data);
    }
    public function _register(usermodel $user)
    {
        $data = $user->checkregister($this->params);
        return response::success($data);
    }
}
  1. 配置路由

//用户路由
route::group([
    'prefix' => 'user',
    'namespace' => 'api\v1',
    'middleware' => 'api.intercept'//api认证拦截中间件
], function ($router) {
    $router->post('_login', 'user@_login');
    $router->post('_register', 'user@_register');
});

到这里api的签名认证就已经设计开发好了!!!感谢观看!!!

本作品采用《cc 协议》,转载必须注明作者和本文链接
本帖由系统于 3年前 自动加精
从零开发一个电商项目,功能包括电商后台、商品 & sku 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 14

写过这样的包

3年前

我承认了,是被你头像吸引进来的

3年前

很完整了,感谢分享

3年前

写过这样的包

3年前

网页 sign 如何操作

3年前

感谢

3年前

向大佬学习

3年前

我承认了,是被你头像吸引进来的

3年前

非常感谢分享。

3年前

illuminate\contracts\container\bindingresolutionexception: target class [api.intercept] does not exist. in file e:\www\blogs\vendor\laravel\framework\src\illuminate\container\container.php on line 805

这个报错 求大佬指点

我知道了 没有注册中间件

3年前

用户每过了86400秒 是不是还需要再次login一下

3年前

用这头像的基本上都是扣脚大汉

3年前

来过

3年前

给大佬ke一个

2年前

file 用中间件来验证接口

2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
网站地图