登录请求次数限制,请求限流方案,通用写法

2022年10月28日14:42:41

目前这个版本是通用写法,也可以针对某个url,可以灵活修改,必须是post请求,代码是在laravel实现的

    public static function login(string $login_name = '', string $password = '', string $code = '')
    {
        $request_ip = request()->ip() == '127.0.0.1' ? request()->header('x-real-ip', '127.0.0.1') : request()->ip();
        $key = 'admin_login:' . sha1(request()->getHost() . '|' . $request_ip);

        try {
            $exists = Redis::exists($key);
            if ($exists) {
                $times = Redis::get($key);
                if ((int)$times >= 5) {
                    throw new Exception('登录超过限制');
                }
            }

            if (empty($login_name)) {
                throw new Exception('登录名不能为空');
            }
            if (empty($password)) {
                throw new Exception('密码不能为空');
            }
            if (empty($code)) {
                throw new Exception('验证码不能为空');
            }
            if (!captcha_check($code)) {
                throw new Exception('验证码错误');
            }

         /**验证密码业务代码*/
            $toked = get_token($Admin->id);
            $res = Admin::where('login_name', $login_name)->update(['token' => $toked, 'token_time' => date('Y-m-d H:i:s', time())]);
            if (empty($res)) {
                throw new Exception('更新token失败');
            }
            $data = [];

            $data['toked'] = $toked; //获取权限数据
            return $data;
        } catch (Exception $e) {
            $exists = Redis::exists($key);
            if ($exists) {
                $times = Redis::get($key);
                Redis::setex($key, 3600, (int)$times + 1);
            } else {
                Redis::setex($key, 3600, 1);
            }
            throw $e;
        }
    }
$key = 'admin_login:' . sha1(request()->getHost() . '|' . $request_ip);

可以把 request()->getHost()改成获取全路径http://www.yd.com/api/admin/login
就可以这针对ip域名,路径创建访问限制

通常这种接口限制都需要限制在中间件里面比较完美,那些登录接口限制,但是一般是通过 throttle组件实现,
但是 throttle目前没找到怎么去处理异常,来限制
使中间件来处理参考:https://www.cnblogs.com/zx-admin/p/16988995.html

posted on 2022-12-19 08:22  zh7314  阅读(193)  评论(0编辑  收藏  举报