当前位置:

Laravel mews-captcha 扩展-api调用安全性提高

本文最后更新于2022-08-24,已超过 1年没有更新,如果文章内容、图片或者下载资源失效,请留言反馈,我会及时处理,谢谢!

温馨提示:本文共1871个字,读完预计5分钟。

新建一个服务类

<?php
namespace App\Services;
use Cache;

class CaptchaCode
{
    public static $captcha_expire = 60 * 3; // 过期时间 3分钟

    /**
     * 生成验证码
     *
     * @param string $config
     * @param int $captcha_expire 过期时间
     * @return  array
     *  $captchaParams =  [
     *      "sensitive" => true,
     *      "key" => "$2y$10$4UTAMBN0hd1V6wP3bVmbhu/PQf/y9Mz6FhFJ/VtU8CkwmRkBF8/cy",// 验证码的hash值
     *      "img" => "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAAkCAYAAABCKP5eAAAA",// base64后的图片
     *  ];
     */
    public static function createCodeAPI(string $config = 'default', $captcha_expire = 180)
    {
        if (!is_numeric($captcha_expire) || $captcha_expire <= 0) {
            $captcha_expire = static::$captcha_expire;
        }

        $captchaParams = app('captcha')->create($config, true);
        $captcha_key = $captchaParams['key'];
        // 缓存起来 这里的键值前缀要和扩展里验证函数captcha_api_check中的验证前缀一致
        Cache::put("captcha_" . md5($captcha_key), 1, $captcha_expire);
        return $captchaParams;
    }

    /**
     * 校验验证码
     * 验证码验证一次即销毁 
     * @param string $captcha_code 验证码
     * @param string $captcha_key 缓存key
     * @return  mixed sting 具体错误(验证不通过) ;
     */
    public static function captchaCheckAPI($captcha_code = '', $captcha_key = '')
    {

        if (!captcha_api_check($captcha_code, $captcha_key)) {
            return ['code' => 1, 'msg' => '验证码错误'];
        }

        return ['code' => 0, 'msg' => ''];
    }
}

 

 

创建图片验证码及验证

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Services\CaptchaCode;

class IndexController extends Controller
{

    public function getCaptcha()
    {
        $data = CaptchaCode::createCodeAPI('resetPassword', 300);
        return ['code' => 0, 'message' => '', 'data' => $data];
    }

    public function captchaCheck(Request $request)
    {
        
        //$this->validate($request, [ 'captcha' => 'required|captcha',]); //通过validate方式验证captcha,不用写逻辑
        $key = $request->input('imgkey', '');
        $captcha = $request->input('captcha', '');
        $check = CaptchaCode::captchaCheckAPI($captcha, $key);
        if ($check["code"] != 0) {
            return ['code' => 1, 'message' => $check["msg"]];
        }
        //处理其他逻辑
        //......
    }

}

 

 

本文链接:,转发请注明来源!
评论已关闭。