简单登陆验证码的后端实现以及登录校验
import com.google.code.kaptcha.impl.DefaultKaptcha;
@Autowired
private DefaultKaptcha producer;
public Result captcha() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
//获取验证码
String text = producer.createText();
logger.info("登录验证码是:"+text);
BufferedImage image = producer.createImage(text);
ImageIO.write(image, "png", out);
String base64bytes = Base64.encode(out.toByteArray());
//该字符串传输至前端放入src即可显示图片
String src = "data:image/png;base64," + base64bytes;
String token = UUID.randomUUID().toString().replace("-", "");
logger.info("验证码的唯一标识是:"+token);
Map<String, Object> map = new HashMap<>(4);
map.put("token", token);
map.put("img", src);
redisUtils.set(token, text,60);
return new Result<>(true, StatusCode.OK,"验证码生成成功",map);
}
public Result login(@RequestBody LoginInfo info) {
...
//前端传过来的验证码
String captcha = info.getCaptcha();
if (StringUtils.isEmpty(captcha)) {
return new Result<>(false, StatusCode.ERROR,"验证码内容不能为空");
}
captcha= captcha .toLowerCase();
//前端传过来的验证码唯一标识
String token = info.getToken();
if (StringUtils.isEmpty(token)) {
return new Result<>(false, StatusCode.ERROR, "唯一标识不能为空");
}
//redis获取的验证码
String captcha_h = (String) redisUtils.get(token);
if (!captcha.equals(captcha_h)) {
return new Result<>(false, StatusCode.ERROR,"验证码输入错误");
}
...
}
token作为唯一标识与验证码内容text对应,将二者对应关系放入redis中;
前端从上诉接口response中拿到img并展示,前端将用户输入的验证码以及上述接口返回的唯一标识token给到后端,后端用唯一标识token去redis中取出验证码内容然后与前端传入的验证码内容比对;