springboot kaptcha验证码
1. 获取验证码在前端保存
2. 在登录接口把验证码穿给后端做验证
下面代码没有提供redis工具类了,SysUser、ApiResult实体
meven kaptcha
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>
登录代码
/** * 登录验证 */ @RestController @Api(description = "登录") public class SysLoginController { // redids工具类 @Autowired private RedisUtil redisUtil; @Autowired DefaultKaptcha producer; /** * 获取验证码 */ @ResponseBody @GetMapping("/captcha") public ApiResult captcha(HttpServletResponse response) throws Exception { // 生成文字验证码 String text = producer.createText(); // 生成图片验证码 BufferedImage image = producer.createImage(text); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ImageIO.write(image, "jpg", outputStream); BASE64Encoder encoder = new BASE64Encoder();// 生成captcha的token String token = System.currentTimeMillis() + "" + CommonUtils.getStringRandom(19); Map<String, Object> map = new HashMap<>(); map.put("img", "data:image/jpeg;base64," + encoder.encode(outputStream.toByteArray())); map.put("token", token); //map.put("text", text);
//保存在redis,设置有效期 redisUtil.set(RedisKey.USER_LOGIN_CAPTCHA + token, text, 60); return ApiResult.success(map); } /** * 登录 */ @PostMapping("/login")public ApiResult login(@RequestBody SysUser user, HttpServletRequest request) { String tokenCaptcha = request.getHeader("token"); String captcha = request.getHeader("captcha"); if (StringUtils.isEmpty(tokenCaptcha)) { return ApiResult.error("token不能为空"); } String redisCaptcha = redisUtil.get(RedisKey.USER_LOGIN_CAPTCHA + tokenCaptcha).toString(); if (StringUtils.notEquals(captcha, redisCaptcha)) { return ApiResult.error("验证码错误"); } return ApiResult.success(true); } }
posted on 2019-06-03 10:48 xiaogui918 阅读(244) 评论(0) 编辑 收藏 举报