简单来说就是用Hutool工具的CaptchaUtil生成一个base64编码,然后返回给前端渲染图片。同时把图片验证码的code存入Redis,在前端请求登录接口的时候先获取Redis中的code和入参的code对比,如果一致则进入下一步操作,否则返回报错提示。

    /**
     * 账号登录图形验证码接口
     * @Author zf
     * @throws IOException
     */
    @RequestMapping("/getCode")
    public ResultMap getCode() {
        //使用Hutool插件定义图形验证码的长和宽,验证码个数,干扰线宽度。
        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(200, 100, 5, 6);
        String imageBase64 = shearCaptcha.getImageBase64();
        //连接Redis
        JedisCommands jedisCommands = JedisUtils.getJedisCommands();
        jedisCommands.setex("login:code:" , 60, shearCaptcha.getCode());
        JedisUtils.close();
        Map<String, Object> data = new HashMap<>();
        data.put("imageBase64", "data:image/jpg;base64," + imageBase64);
        return resultMap.err("").code(0).info(data);
    }

    /**
     * 账号登录接口
     * @Author zf
     * @throws IOException
     */
    @RequestMapping("/login")
    public ResultMap login(@RequestBody SysUserEntity user){
        // 从redis里取出图形验证码
        String sessionCode = JedisUtils.getJedisCommands().get("login:code:");
        if(StrUtil.isBlank(sessionCode)){
            return resultMap.err("图形验证码不存在请刷新页面!").code(-1).info("");
        }
        if (StrUtil.isBlank(user.getCODE())) {
            return resultMap.err("图形验证码不能为空!").code(-1).info("");
        }
        // 比对图形验证码
        if (!sessionCode.equals(user.getCODE())) {
            return resultMap.err("图形验证码错误!").code(-1).info("");
        }
        /** --------------------------------- 以下忽略 ---------------------------------*/
    }
最后修改:2023 年 02 月 16 日
给我一点小钱钱也很高兴啦!o(* ̄▽ ̄*)ブ