验证码技术原理
- 包装秒杀令牌前置,需要验证码来错峰;
- 数学公式验证码生成器;
验证码实现
验证码生成接口
- 生成的图片直接放到 HTTP Response 的 OutputStream 中;
- 接口的 URL 直接放到 img 标签的 src 属性中;
- 生成的验证码的值,要放在 Redis 中;
@RequestMapping(value = "/generateverifycode", method = {RequestMethod.GET})
@ResponseBody
public void generateVerifyCode(HttpServletResponse response) throws BusinessException, IOException {
String token = httpServletRequest.getParameterMap().get("token")[0];
if (StringUtils.isEmpty(token)) {
throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用户还未登录,不能生成验证码");
}
UserModel userModel = (UserModel) redisTemplate.opsForValue().get(token);
if (userModel == null) {
throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用户还未登录,不能生成验证码");
}
// 生成验证码
Map<String,Object> map = CodeUtil.generateCodeAndPic();
// 把验证码的码值写到 Redis 中
redisTemplate.opsForValue().set("verify_code_" + userModel.getId(), map.get("code"));
redisTemplate.expire("verify_code_" + userModel.getId(), 10, TimeUnit.MINUTES);
// 把验证码的图片写到 HTTP Response 中
ImageIO.write((RenderedImage) map.get("codePic"), "jpeg", response.getOutputStream());
}
生成令牌之前先校验验证码的正确性
@RequestMapping(value = "/generatetoken", method = {RequestMethod.POST}, consumes = {CONTENT_TYPE_FORMED})
@ResponseBody
public CommonReturnType generateToken(@RequestParam(name = "itemId") Integer itemId,
@RequestParam(name = "promoId") Integer promoId,
@RequestParam(name = "verifyCode") String verifyCode) throws BusinessException {
String token = httpServletRequest.getParameterMap().get("token")[0];
if (StringUtils.isEmpty(token)) {
throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用户还未登录,不能下单");
}
UserModel userModel = (UserModel) redisTemplate.opsForValue().get(token);
if (userModel == null) {
throw new BusinessException(EmBusinessError.USER_NOT_LOGIN, "用户还未登录,不能下单");
}
// 通过验证码验证有效性
String redisVerifyCode = (String) redisTemplate.opsForValue().get("verify_code_" + userModel.getId());
if (StringUtils.isEmpty(redisVerifyCode)) {
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "请求非法");
}
if (!StringUtils.equalsIgnoreCase(redisVerifyCode, verifyCode)) {
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "请求非法,验证码错误");
}
// 生成秒杀令牌
String promoToken = promoService.generateSecondKillToken(promoId, itemId, userModel.getId());
if (promoToken == null) {
throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "生成秒杀令牌失败");
}
return CommonReturnType.create(promoToken);
}