图形验证码
一、maven依赖
<dependency>
<groupId>com.github.whvcse</groupId>
<artifactId>easy-captcha</artifactId>
<version>1.6.2</version>
</dependency>
二、图片验证码接口
样式根据自己需要调整
@GetMapping(value = "/get",produces = "image/jpeg")
@ApiOperation("验证码")
public void captcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
try {
httpServletResponse.setContentType("image/gif");
httpServletResponse.setHeader("Pragma", "No-cache");
httpServletResponse.setHeader("Cache-Control", "no-cache");
httpServletResponse.setDateHeader("Expires", 0);
// 三个参数分别为宽、高、位数
SpecCaptcha specCaptcha = new SpecCaptcha (100, 40, 4);
// 设置字体
specCaptcha.setFont(new Font("楷体", Font.PLAIN, 28));
// 设置类型,纯数字、纯字母、字母数字混合
specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
// 获取验证码文本内容 .toLowerCase();用户可以支持大小写验证码
String text = specCaptcha.text().toLowerCase();
log.info("验证码:{}",text);
String uuid = UUID.randomUUID().toString();
log.info("UUID:{}",uuid);
// redis缓存验证码
redisTemplate.opsForValue().set("contract"+uuid,text, 600L, TimeUnit.SECONDS);
httpServletResponse.setHeader("Access-Control-Expose-Headers","UUID");
httpServletResponse.addHeader("UUID", uuid);
//写入流
ServletOutputStream outputStream = httpServletResponse.getOutputStream();
specCaptcha.out(outputStream);
try {
outputStream.flush();
} finally {
outputStream.close();
}
} catch (Exception e) {
log.info("验证码错误:{}",e);
}
//-------------------生成验证码 end -------------------//
}
验证码效果图
三、登录接口
验证码验证逻辑
@PostMapping("/login")
@ApiOperation("登录")
public ReturnData accountAuthLogin(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody AccountAuthLoginDTO accountAuthLoginDTO) {
//验证验证码
if (StringUtils.isNotBlank(accountAuthLoginDTO.getUuid())&&StringUtils.isNotBlank(accountAuthLoginDTO.getCode())){
String code = (String) redisUtils.get("contract" + accountAuthLoginDTO.getUuid());
String adCode=accountAuthLoginDTO.getCode().toLowerCase();//对验证码内容转换为小写
if (!adCode.equals(code)) {
//返回验证码错误
return new ReturnData(new Date(), HttpStatus.INTERNAL_SERVER_ERROR.value(), "验证码输入错误", httpServletRequest.getRequestURI(), new AccountAuthLoginVO());
}
}
//如果验证码正确,进行验证用户名姓名执行登录操作
//进行登录
return new ReturnData(new Date(), HttpStatus.OK.value(), "登录成功", httpServletRequest.getRequestURI(), new AccountAuthLoginVO());
}
}
四、测试
不要忘记把拦截器放开这两个接口
接口验证:输入验证码内容及调用验证码接口生成的uuid即可
以上就是图形验证码的使用