ruoyi-vue前后端分离版本验证码实现思路

时隔三个月,再次拿起我的键盘。

前言

ruoyi-vue是若依前后端分离版本的快速开发框架,适合用于项目开始搭建后台管理系统。本篇文章主要介绍其验证码实现的思路。

一、实现思路简介

1、后端会生成一个表达式,比如1 + 2 = ? @ 3,以@符号为分隔符,前面是问题,后面是答案。
2、将问题转换为流,生成表达式图片之后,把图片传到前端进行展示。
3、会生成一个uuid当成key,答案当成value,存进redis缓存数据库中。
4、uuid也会一起传到前端进行隐藏域(input)存储。
5、用户根据问题,把答案填写到表单中,将答案和uuid一起传回后端。
6、根据传回的uuid去redis中拿到正确答案,将用户答案和正确答案进行对比,若相同则验证码正确,否则失败。
7、验证码正确则验证用户名和密码,否则刷新验证码重新填写答案进行验证。

二、后端

2.1 接口位置

后端验证码生成接口在CaptchaController控制器中,如图:

ruoyi-vue前后端分离版本验证码实现思路_第1张图片

代码如下:

/**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        ajax.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled)
        {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = RuoYiConfig.getCaptchaType();
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

三、前端

3.1 代码位置

前端代码在login.vue文件中,如图:

ruoyi-vue前后端分离版本验证码实现思路_第2张图片

获取验证码代码如下:
ruoyi-vue前后端分离版本验证码实现思路_第3张图片

提交表单代码如下:

ruoyi-vue前后端分离版本验证码实现思路_第4张图片

总结

若依的验证码实现思路十分通俗易懂,值得大家研究学习!

你可能感兴趣的:(JavaWeb,vue等前端知识,vue.js,okhttp,前端,java,spring,boot)