1、引入依赖

<dependency>
  <groupId>com.github.whvcse</groupId>
  <artifactId>easy-captcha</artifactId>
  <version>1.6.2</version>
</dependency>

2、验证码请求接口

@RequestMapping("/captcha")
@ResponseBody
public JSONObject captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
    String key = UUID.randomUUID().toString();
    captcha.setLen(3);
    captcha.getArithmeticString();
    captcha.setHeight(30);
    captcha.setWidth(146);
    String res = captcha.text();
    stringRedisTemplate.opsForValue().set(key,res,300, TimeUnit.SECONDS);
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("key", key);
    jsonObject.put("captcha", captcha.toBase64());
    return jsonObject;
}

3、验证码验证逻辑

@RequestMapping(value = "/login", method = RequestMethod.POST)
public BaseResult createAuthenticationToken(@RequestBody AuthenticationRequest authenticationRequest, HttpServletRequest request)
throws AuthenticationException {
    try {

      // 验证验证码

      if (StringUtils.isEmpty(authenticationRequest.getCaptcha())) {
          return BaseResult.fail("验证码不能为空!");
      }

      String captcha = stringRedisTemplate.opsForValue().get(authenticationRequest.getCaptchaKey());
      if (!authenticationRequest.getCaptcha().equals(captcha)) {
          return BaseResult.fail("验证码不正确!");
      }

      final AuthenticationResponse response = authService.login(authenticationRequest.getUsername(),
      authenticationRequest.getPassword());

      taskExecutor.submit(() -> {
        String ip = Optional.ofNullable(request.getHeader("X-Forwarded-For")).orElse(request.getRemoteAddr());
        LoginLog loginLog = new LoginLog();
        loginLog.setDeptName(response.getUser().getDeptName());
        loginLog.setLoginName(response.getUser().getLoginName());
        loginLog.setLogintime(new Date());
        loginLog.setToken(response.getToken());
        loginLog.setIp(ip);
        loginLogMapper.insert(loginLog);
      });

      return BaseResult.success(response);
    } catch (Exception ex) {
        return BaseResult.fail(ex.getMessage());
    }

}

4、前端代码


<div class="info_put_b">
  <span>验证码:</span>
  <input class="code" 
  type="text" style="top: 205px;width: 100px" 
  [(ngModel)]="signIn.captcha" name="captcha" autocomplete="new-password" />
  <img width="146" height="30" src="{{captcha}}" (click)="getcaptcha()">
</div>

5、效果

upload successful



JAVA      算术验证码

本博客所有文章除特别声明外,均采用 CC BY-SA 3.0协议 。转载请注明出处!