EasyCaptcha生成验证码

 

添加依赖

 <dependency>
            <groupId>com.github.whvcse</groupId>
            <artifactId>easy-captcha</artifactId>
            <version>1.6.2</version>
        </dependency>

验证码使用流程:

需要将验证码存入redis中,当前端获取验证码时,顺便传过一个码过来。后端将码添加一个前缀后 ,用于该验证码保存到redis中的key值,该验证包保存时需要带一个过期时间,默认单位是秒。在这个案例中,更多常量写在配置文件中。

 @ApiOperation("获取验证码")
    @GetMapping(value = "/code")
    public ResponseEntity<Object> getCode(){
        // 算术类型 https://gitee.com/whvse/EasyCaptcha
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算,默认是两位
        captcha.setLen(2);
        // 获取运算的结果
        String result ="";
        try {
            result = new Double(Double.parseDouble(captcha.text())).intValue()+"";
        }catch (Exception e){
            result = captcha.text();
        }

      /**
     * 简化的UUID,去掉了横线
     * hutools
     * @return 简化的UUID,去掉了横线
     */
        String uuid = properties.getCodeKey() + IdUtil.simpleUUID();
        // 保存
        redisUtils.set(uuid, result, expiration, TimeUnit.MINUTES);
        // 验证码信息
        Map<String,Object> imgResult = new HashMap<String,Object>(2){{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};
        return ResponseEntity.ok(imgResult);
    }

 

前端请求

export function getCodeImg() {

  return request({

    url: 'auth/code',

    method: 'get'

  })

}

 

getCode() {

      getCodeImg().then(res => {

        this.codeUrl = res.img

        this.loginForm.uuid = res.uuid

      })

    }

登录验证验证码

// 查询验证码
        String code = (String) redisUtils.get(authUser.getUuid());
        // 清除验证码
        redisUtils.del(authUser.getUuid());
        if (StringUtils.isBlank(code)) {
            throw new BadRequestException("验证码不存在或已过期");
        }
        if (StringUtils.isBlank(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) {
            throw new BadRequestException("验证码错误");
        }

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值