SpringBoot集成Kaptcha实现图形验证码

Myth丶恋晨 2022-03-22 02:19 1081阅读 0赞

前言

相信大家在浏览网页的时候,经常会碰到人机校验。很经典的要属Google的人机校验,用多张图片进行点击校验。可以说是对于我们人类来说就是很烦的啦。烦归烦,但是为了安全着想,我们还是需要为自己的项目加上验证码机制,特别是一些防刷的接口调用下。今天我们就来学习简单的图形验证码实现。

环境准备

SpringBoot DEMO,Maven项目。
创建SpringBoot项目很简单,Intellij IDEA旗舰版可直接创建。

引入kaptcha maven依赖

  1. <!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
  2. <dependency>
  3. <groupId>com.github.penggle</groupId>
  4. <artifactId>kaptcha</artifactId>
  5. <version>2.3.2</version>
  6. </dependency>

基本配置

application.yml

  1. kaptcha:
  2. border: "yes" // 是否有边框,默认为yes,可选yes、no
  3. border.color: 105,179,90 //边框颜色
  4. textproducer:
  5. font:
  6. color: blue // 验证码字体颜色
  7. size: 30 // 文本字符大小
  8. names: 宋体,楷体,微软雅黑 //文本字体样式
  9. char:
  10. length: 4 //验证码文本字符长度
  11. image:
  12. width: 120 // 图片宽度
  13. height: 40 // 图片高度
  14. session:
  15. key: code // 存储session key

KaptchaConfig.java

  1. /**
  2. * @Description Kaptcha配置类 用于生成图形验证码
  3. * @Author chenlinghong
  4. * @Date 2019/1/25 10:31
  5. **/
  6. @Component
  7. public class KaptchaConfig {
  8. @Value("${kaptcha.border}")
  9. private String border;
  10. @Value("${kaptcha.border.color}")
  11. private String borderColor;
  12. @Value("${kaptcha.textproducer.font.color}")
  13. private String textproducerFontColor;
  14. @Value("${kaptcha.textproducer.font.size}")
  15. private String textproducerFontSize;
  16. @Value("${kaptcha.textproducer.font.names}")
  17. private String textproducerFontNames;
  18. @Value("${kaptcha.textproducer.char.length}")
  19. private String textproducerCharLength;
  20. @Value("${kaptcha.image.width}")
  21. private String imageWidth;
  22. @Value("${kaptcha.image.height}")
  23. private String imageHeight;
  24. @Value("${kaptcha.session.key}")
  25. private String sessionKey;
  26. @Bean
  27. public DefaultKaptcha getDefaultKapcha(){
  28. DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
  29. Properties properties = new Properties();
  30. properties.setProperty("kaptcha.border", border);
  31. properties.setProperty("kaptcha.border.color", borderColor);
  32. properties.setProperty("kaptcha.textproducer.font.color", textproducerFontColor);
  33. properties.setProperty("kaptcha.textproducer.font.size", textproducerFontSize);
  34. properties.setProperty("kaptcha.textproducer.font.names", textproducerFontNames);
  35. properties.setProperty("kaptcha.textproducer.char.length", textproducerCharLength);
  36. properties.setProperty("kaptcha.image.width", imageWidth);
  37. properties.setProperty("kaptcha.image.height", imageHeight);
  38. properties.setProperty("kaptcha.session.key", sessionKey);
  39. Config config = new Config(properties);
  40. defaultKaptcha.setConfig(config);
  41. return defaultKaptcha;
  42. }
  43. }

从application.yml中获取到配置属性,通过@Bean注入返回值为DefaultKaptcha的方法,方法体内获取到相应的properties进行配置DefaultKaptcha。即可在其他类中进行注入此类,使用。

获取图形验证码接口

ImageController.java

  1. @CrossOrigin
  2. @Slf4j
  3. @RestController
  4. @RequestMapping(value = "/img")
  5. public class ImageController {
  6. /* 注入Kaptcha */
  7. @Autowired
  8. private DefaultKaptcha defaultKaptcha;
  9. @GetMapping(value = "/code")
  10. public Result defaultKaptcha(HttpServletRequest request, HttpServletResponse response){
  11. byte[] captchaChallengeAsJpeg;
  12. ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
  13. /**
  14. * 生成验证码字符串并保存到session中
  15. */
  16. String createText = defaultKaptcha.createText();
  17. HttpSession session = request.getSession();
  18. session.setAttribute(SessionConstant.IMAGE_CODE, createText);
  19. /**
  20. * 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
  21. */
  22. BufferedImage challenge = defaultKaptcha.createImage(createText);
  23. try {
  24. ImageIO.write(challenge,"jpg",jpegOutputStream);
  25. } catch (IOException e) {
  26. log.error("生成图形验证码失败",e);
  27. throw new BusinessException(ErrorEnum.CRATE_IMAGE_ERROR); // 抛出异常,可以不用关心
  28. }
  29. /**
  30. * 定义response输出类型为image/jpeg类型,使用response输出流输出图片的byte数组
  31. */
  32. captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
  33. response.setHeader("Cache-Control", "no-store");
  34. response.setHeader("Pragma", "no-cache");
  35. response.setDateHeader("Expires",0);
  36. response.setContentType("image/jpeg");
  37. try {
  38. ServletOutputStream servletOutputStream = response.getOutputStream();
  39. servletOutputStream.write(captchaChallengeAsJpeg);
  40. servletOutputStream.flush();
  41. servletOutputStream.close();
  42. } catch (IOException e) {
  43. log.error("输出验证码失败",e);
  44. throw new BusinessException(ErrorEnum.CRATE_IMAGE_ERROR); // 抛出异常,可以不用关心
  45. }
  46. return ResultUtil.success(); // 返回成功提示信息
  47. }
  48. }

通过文件流的方式,直接输出验证码图片。

请求获取

启动项目,浏览器访问 http://127.0.0.1:8080/img/code
在这里插入图片描述

参考链接

1、Kaptcha 和 JCaptcha 使用介绍和实例
2、Google Code - Kaptcha

发表评论

表情:
评论列表 (有 0 条评论,1081人围观)

还没有评论,来说两句吧...

相关阅读