若依框架讲解后端利用DefaultKaptcha生成验证码及校验

pom文件中引入DefaultKaptcha的依赖
            <dependency>
                <groupId>com.github.penggle</groupId>
                <artifactId>kaptcha</artifactId>
                <version>2.3.2</version>
            </dependency>

Kaptcha 是一个可高度配置的实用验证码生成工具,可自由配置的选项如

  • 验证码的字体
  • 验证码字体的大小
  • 验证码字体的字体颜色
  • 验证码内容的范围(数字,字母,中文汉字!)
  • 验证码图片的大小,边框,边框粗细,边框颜色
  • 验证码的干扰线
  • 验证码的样式(鱼眼样式、3D、普通模糊、…)

CaptchaConfig类中配置验证码相关的参数(字符验证码)

在这里插入图片描述
若依的配置文件在这里
在这里插入图片描述
若依的验证码操作处理
在这里插入图片描述
在这里插入图片描述
提供了一个 getCode() 方法,用于生成验证码图片并将验证码信息保存到 Redis 缓存中。
在这里插入图片描述
首先判断是否启用了验证码功能,如果没有启用则直接返回一个 AjaxResult 对象,其中包含 captchaEnabled 字段(bool 类型),值为 false。
在这里插入图片描述
在这里插入图片描述
如果启用了验证码,则生成一个随机的 uuid 并将其作为验证码存储的 key,将验证码的值作为 value 存储到 Redis 缓存中,同时将验证码图片以 base64 格式返回给前端。

/**
 * 验证码操作处理
 * 
 * @author core
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    private Producer captchaProducer; // 验证码生成器,用于生成字符验证码图片
    //自动装配 Spring 框架的相关注解(例如 @RestController、@Resource、@Autowired),这些注解在程序启动时会被解析,在需要时自动创建对象并注入依赖。
    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath; // 验证码生成器,用于生成数学计算验证码图片

    @Autowired
    private RedisCache redisCache; // Redis 缓存服务,用于保存验证码信息
    
    @Autowired
    private ISysConfigService configService;   // 配置服务,用于获取是否启用验证码等信息
    /**
     * 生成验证码图片
     * @param response HTTP 响应对象
     * @throws IOException IO 异常
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException
    {
        AjaxResult ajax = AjaxResult.success(); // 创建 AjaxResult 对象,用于封装返回到前端的数据
        boolean captchaEnabled = configService.selectCaptchaEnabled();  // 获取是否启用验证码
        ajax.put("captchaEnabled", captchaEnabled);  // 将是否启用验证码的值保存到 AjaxResult 对象中,以返回到前端
        if (!captchaEnabled) // 如果未启用验证码,直接返回 AjaxResult 对象
        {
            return ajax;
        }

        // 生成验证码信息
        String uuid = IdUtils.simpleUUID();    // 随机生成 UUID 作为 Key
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid; // 构造验证码 Key,用于在缓存中保存验证码信息

        String capStr = null, code = null; // 验证码字符串和验证码值
        BufferedImage image = null; // 验证码图片

        // 生成验证码图片和验证码值
        String captchaType = CoreConfig.getCaptchaType(); // 获取验证码类型,可选值有:"char" 和 "math"
        if ("math".equals(captchaType)) // 如果验证码类型为数学计算类型
        {
            String capText = captchaProducerMath.createText();  // 生成一个包含数学计算公式的验证码字符串
//            System.out.println(capText);
//            4-2=?@2
            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); // 将验证码信息存储到缓存中,验证码 Key 为 verifyKey,验证码值为 code
        // 转换验证码图片流,并以 base64 格式返回
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return AjaxResult.error(e.getMessage());
        }

        ajax.put("uuid", uuid); // 将 UUID 作为 'uuid' 键保存到 AjaxResult 中,以返回到前端
        ajax.put("img", Base64.encode(os.toByteArray()));// 将验证码图片的 base64 编码保存到 'img' 键中,以返回到前端
        return ajax;
    }
}

前端页面利用Img标签的src属性,根据Base64编码格式数据获取验证码图片显示。

    // 获取验证码方法
    getCode() {
      getCodeImg().then(res => {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
      });
    },
    <!-- 利用img标签,src属性根据Base64编码格式数据来获取验证码图。 -->
    <div class="login-code">
        <img :src="codeUrl" @click="getCode" class="login-code-img"/>
    </div>

校验验证码
在这里插入图片描述

 public void validateCaptcha(String username, String code, String uuid)
    {
        boolean captchaEnabled = configService.selectCaptchaEnabled();  // 获取是否启用验证码
        if (captchaEnabled) {   // 如果启用验证码
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");  // 构建缓存中验证码的 key
            String captcha = redisCache.getCacheObject(verifyKey);  // 从缓存中获取验证码信息
            redisCache.deleteObject(verifyKey);    // 从缓存中删除验证码信息
            if (captcha == null) {  // 如果验证码信息为空
                // 记录登录失败日志,并抛出 CaptchaExpireException 异常,表示验证码过期
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) { // 如果用户输入的验证码与缓存中的验证码不匹配
                // 记录登录失败日志,并抛出 CaptchaException 异常,表示验证码错误
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

以上就是若依框架生成验证码的功能以及校验过程。

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
1. 引入依赖 在pom.xml中添加以下依赖: ``` <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>easy-captcha-spring-boot-starter</artifactId> <version>2.4.4</version> </dependency> ``` 2. 配置参数 在application.properties或application.yml中添加以下配置: ``` # 验证码配置 easy.captcha.width=130 # 验证码宽度 easy.captcha.height=48 # 验证码高度 easy.captcha.length=4 # 验证码字符长度 easy.captcha.font-size=30 # 验证码字体大小 easy.captcha.expire=120 # 验证码有效期,单位秒 ``` 3. 生成验证码 在登录接口中生成验证码,代码如下: ```java @RestController public class LoginController { @Autowired private Producer captchaProducer; @GetMapping("/captcha") public Map<String, String> getCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception { // 生成验证码 String text = captchaProducer.createText(); BufferedImage image = captchaProducer.createImage(text); // 将验证码转换成base64格式 ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(image, "png", bos); byte[] bytes = bos.toByteArray(); String base64Img = "data:image/png;base64," + Base64.getEncoder().encodeToString(bytes); // 将验证码存入session中 HttpSession session = request.getSession(); session.setAttribute("captcha", text); // 返回结果 Map<String, String> result = new HashMap<>(); result.put("captcha", base64Img); return result; } @PostMapping("/login") public String login(HttpServletRequest request, @RequestParam String username, @RequestParam String password, @RequestParam String captcha) { // 校验验证码 HttpSession session = request.getSession(); String captchaInSession = (String) session.getAttribute("captcha"); if (!captcha.equals(captchaInSession)) { return "验证码错误"; } // 校验用户名和密码 if ("admin".equals(username) && "123456".equals(password)) { return "登录成功"; } else { return "用户名或密码错误"; } } } ``` 在getCaptcha方法中,首先使用captchaProducer.createText()方法生成验证码的文字,然后使用captchaProducer.createImage(text)方法生成验证码图片。接着,将验证码图片转换成base64格式,并将验证码文字存入session中,最后返回包含验证码图片的base64编码的结果。 在login方法中,先从session中获取验证码文字,然后与用户输入的验证码比较。如果一致,则校验用户名和密码,并返回登录结果。 4. 前端展示 在前端页面中,使用<img>标签展示验证码,代码如下: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <h1>Login</h1> <form action="/login" method="post"> <div> <label for="username">Username:</label> <input type="text" name="username" id="username"> </div> <div> <label for="password">Password:</label> <input type="password" name="password" id="password"> </div> <div> <label for="captcha">Captcha:</label> <input type="text" name="captcha" id="captcha"> <img src="" id="captchaImg"> <a href="#" onclick="refreshCaptcha()">refresh</a> </div> <input type="submit" value="Login"> </form> <script> function refreshCaptcha() { // 刷新验证码 var captchaImg = document.getElementById("captchaImg"); var url = "/captcha?" + new Date().getTime(); fetch(url).then(function (response) { return response.json(); }).then(function (data) { captchaImg.src = data.captcha; }); } // 页面加载时刷新验证码 window.onload = function () { refreshCaptcha(); }; </script> </body> </html> ``` 在页面加载时,使用fetch方法调用/captcha接口获取验证码图片的base64编码,并将其设置为<img>标签的src属性。当点击刷新链接时,再次调用/captcha接口获取新的验证码图片,并刷新<img>标签的src属性。在提交表单时,将用户输入的验证码一并提交给后端进行校验。 这样,就完成了使用easycaptcha生成验证码,并将其以base64格式传给前端登录页面的后端代码和前端代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

左魇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值