基本流程
细分一共有7步。
uuid是重点,将会贯穿整个验证码的生命周期。后端会根据uuid找到真实验证码进行比对。
getCode() { getCodeImg().then(res => { this.codeUrl = "data:image/gif;base64," + res.img; this.loginForm.uuid = res.uuid; }); },
/** ● 生成验证码 */ @GetMapping("/captchaImage") public AjaxResult getCode(HttpServletResponse response) throws IOException{ // 生成验证码信息 String uuid = IdUtils.simpleUUID(); String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid; String capStr = null; BufferedImage image = null; // 生成验证码 可以配置多种类型的验证码 if ("math".equals(captchaType)){ capStr = captchaProducerMath.createText(); image = captchaProducerMath.createImage(capText); } else if ("char".equals(captchaType)){ capStr = captchaProducer.createText(); image = captchaProducer.createImage(capStr); } // 存入redis 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()); } AjaxResult ajax = AjaxResult.success(); ajax.put("uuid", uuid); // 转码base64 ajax.put("img", Base64.encode(os.toByteArray())); return ajax; }
带上 验证码 和 uuid 一起登录
password: "admin123" username: "admin" uuid: "66ae1f227bf245a8b6ec2e6c00fb6189" code: "1234"
先校验验证码,再校验账号密码。
@PostMapping("/login") public AjaxResult login(@RequestBody LoginBody loginBody) { AjaxResult ajax = AjaxResult.success(); String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid()); ajax.put(Constants.TOKEN, token); return ajax; }
/** * 登录验证 * * @param username 用户名 * @param password 密码 * @param code 验证码 * @param uuid 唯一标识 * @return 结果 */ public String login(String username, String password, String code, String uuid) { String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid; // 根据UUID 去redis取出正确的验证码====================================================== String captcha = redisCache.getCacheObject(verifyKey); redisCache.deleteObject(verifyKey); // 验证redis的验证码和用户输入的验证码是否相等。 // 验证账号密码 // 验证错误就抛出异常 // 生成token return tokenService.createToken(loginUser); }
这是一个简单的登录验证码实现流程,具体实现可能因技术栈和需求而有所不同。但是流程基本上都是相同的。