使用图片验证码进行登录验证
需求:后端系统登录时使用图片验证码验证登录
效果:
使用 4 位数字加字母组合验证码登录,相关代码为:
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
@RequestMapping("/getCode")
public ResultVO getCode(HttpServletRequest request, HttpServletResponse response) {
String imageBase64 = "";
Map<String, String> result = new HashMap<>();
try {
// 定义图片大小
LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 300);
response.setContentType("image/jpeg");
response.setHeader("Pragma", "No-cache");
imageBase64 = "data:image/png;base64," + captcha.getImageBase64();
String code = captcha.getCode();
logger.info("生成的图片验正码:{}", code);
String codeKey = UUID.randomUUID().toString();
redisSupport.set(codeKey, captcha.getCode());
result.put("code",imageBase64);
result.put("codeKey", codeKey);
} catch (Exception e) {
logger.error("生成图片验正码异常", e);
return new ResultVO<>(ResultVO.FAIL, "获取图片失败");
}
return new ResultVO<>(result, ResultVO.SUCCESS, "获取图片成功");
}
这部分代码实现的是生成图片验证码的功能,使用的是 hutool 的工具包,需要以 key-value 的形式将生成的图片和用户关联起来,所以我们将结果以 Map 的形式返回给前端。其中使用的 redisSupport 可根据实际情况进行替换,其实就是 Redis 的一个工具包,后续会单独贴出来。 Redis 工具包请参考文章:Redis 工具实用篇_jiaomubai的博客-CSDN博客
正式登录接口的代码如下:
@PostMapping("/login")
public void login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam("code") String code, @RequestParam("codeKey") String codeKey, HttpServletResponse resp, HttpServletRequest request) {
JSONObject result = new JSONObject();
try {
String redisCode = (String) redisSupport.get(codeKey);
log.info("redisCode:{}",redisCode);
if(StringUtils.isEmpty(code) || StringUtils.isEmpty(redisCode) || !code.equals(redisCode)){
result.put("error_description", "验证码错误");
result.put("error", "invalid_grant");
resp.setStatus(400);
redisSupport.del(codeKey);
return;
}
} catch (Exception e) {
log.error("登录接口错误,错误信息:{}", e);
} finally {
try {
resp.setContentType(ContentType.JSON.getValue());
ServletOutputStream out = resp.getOutputStream();
OutputStreamWriter ow = new OutputStreamWriter(out, "UTF-8");
ow.write(result.toJSONString());
ow.flush();
ow.close();
} catch (Exception e) {
log.error("登录接口错误,错误信息:{}", e);
}
}
}
其中入参中 username 为登录的用户名,password 为登录密码,code 为用户输入的图片验证码的答案,codekey 为与 code 关联的 key,因为在获取验证码的接口中(/getCode)我们已经将 code 和 codekey 存储在了 Redis 中,所以此处可直接根据 codekey 去获取 Redis 中的与 codekey 对应的验证码,之后与用户输入的 code 进行比较即可。其中使用的 redisSupport 可根据实际情况进行替换,其实就是 Redis 的一个工具包,后续会单独贴出来。 Redis 工具包请参考文章:Redis 工具实用篇_jiaomubai的博客-CSDN博客
还有一种使用简单运算的登录验证方式在下一篇文章中说明~
还没有评论,来说两句吧...