• 常用工具类之使用kaptcha生成验证码


    验证码的作用

    防止恶意破解密码、刷票、论坛灌水、刷页。

    有效防止某个黑客对某一个特定注册用户用特定程序暴力破解方式进行不断的登录尝试,实际上使用验证码是现在很多网站通行的方式(比如招商银行的网上个人银行,百度社区),我们利用比较简易的方式实现了这个功能。虽然登录麻烦一点,但是对网友的密码安全来说这个功能还是很有必要,也很重要。但我们还是 提醒大家要保护好自己的密码 ,尽量使用混杂了数字、字母、符号在内的 6 位以上密码,不要使用诸如 1234 之类的简单密码或者与用户名相同、类似的密码 ,免得你的账号被人盗用给自己带来不必要的麻烦。

    验证码通常使用一些线条和一些不规则的字符组成,主要作用是为了防止一些黑客把密码数据化盗取。

    Kaptcha 简介

    Kaptcha 是一个可高度配置的实用验证码生成工具,可自由配置的选项如:

    • 验证码的字体
    • 验证码字体的大小
    • 验证码字体的字体颜色
    • 验证码内容的范围(数字,字母,中文汉字!)
    • 验证码图片的大小,边框,边框粗细,边框颜色
    • 验证码的干扰线
    • 验证码的样式(鱼眼样式、3D、普通模糊、...)

     springboot整合kaptcha

    1.登录验证码

    使用kaptcha来实现

    pom.xml

    1.   <dependency>
    2.             <groupId>com.github.axet</groupId>
    3.             <artifactId>kaptcha</artifactId>
    4.             <version>0.0.9</version>
    5.         </dependency>

    config添加配置

    1. import com.google.code.kaptcha.impl.DefaultKaptcha;
    2. import com.google.code.kaptcha.util.Config;
    3. import org.springframework.context.annotation.Bean;
    4. import org.springframework.context.annotation.Configuration;
    5.  
    6. import java.util.Properties;
    7.  
    8. /*
    9. * 验证码配置
    10. * */
    11. @Configuration
    12. public class KaptchaConfig {
    13.  
    14.     @Bean
    15.     public DefaultKaptcha producer(){
    16.         Properties properties = new Properties();
    17.         properties.put("kaptcha.border","no");
    18.         properties.put("kaptcha.textproducer.font.color","black");
    19.         properties.put("kaptcha.textproducer.char.space","5");
    20.         Config config = new Config(properties);
    21.         DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
    22.         defaultKaptcha.setConfig(config);
    23.         return defaultKaptcha;
    24.     }
    25. }

    controller生成

    1. import com.google.code.kaptcha.Constants;
    2. import com.google.code.kaptcha.Producer;
    3. import org.apache.commons.math3.stat.descriptive.summary.Product;
    4. import org.apache.poi.util.IOUtils;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.web.bind.annotation.GetMapping;
    7. import org.springframework.web.bind.annotation.RestController;
    8.  
    9. import javax.imageio.ImageIO;
    10. import javax.servlet.ServletException;
    11. import javax.servlet.ServletOutputStream;
    12. import javax.servlet.http.HttpServletRequest;
    13. import javax.servlet.http.HttpServletResponse;
    14. import java.awt.image.BufferedImage;
    15. import java.io.IOException;
    16.  
    17. @RestController
    18. public class SysLoginController {
    19.     @Autowired
    20.     private Producer producter;
    21.    @GetMapping("/captcha.jpg")
    22.     public void  captcha(HttpServletResponse response, HttpServletRequest request)throws ServletException, IOException{
    23.        response.setHeader("Cache-Control","no-store,no-cache");
    24.        response.setContentType("image/jpeg");
    25.        //生成文字验证码
    26.        String text = producter.createText();
    27.        //生成图片验证码
    28.        BufferedImage image = producter.createImage(text);
    29.        //保存验证码到session
    30.        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
    31.        ServletOutputStream out = response.getOutputStream();
    32.        ImageIO.write(image,"jpg",out);
    33.        IOUtils.closeQuietly(out);
    34.    }
    35. }

    或者使用penggle包下的kaptcha

    pom文件中导入kaptcha依赖
             新建springboot项目,并在其pom.xml中导入kaptcha依赖:

    1.   <dependency>
    2.         <groupId>com.github.penggle</groupId>
    3.         <artifactId>kaptcha</artifactId>
    4.         <version>2.3.2</version>
    5.  </dependency>

    创建前端页面与跳转页面
            前端页面index.html

    1. <h2>kaptcha验证码验证</h2>
    2.   <form action="/loginh" method="post">
    3.       <input type="text" name="verifyCode" placeholder="请输入验证码" required="true">
    4.       <img alt="单击图片刷新!" class="pointer" src="/common/kaptcha"
    5.            onclick="this.src='/common/kaptcha?d='+new Date()*1">
    6.       </br>
    7.       <button type="submit" value="submit">登陆</button>
    8.   </form>

             跳转页面success.html

    1. <!DOCTYPE html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4.     <meta charset="UTF-8">
    5.     <title>Title</title>
    6. </head>
    7. <body>
    8. <h2>success</h2>
    9. </body>
    10. </html>

      注入keptcha配置类
             创建配置类KaptchaConfig.java

    1. import com.google.code.kaptcha.impl.DefaultKaptcha;
    2. import com.google.code.kaptcha.util.Config;
    3. import org.springframework.context.annotation.Bean;
    4. import org.springframework.stereotype.Component;
    5. import java.util.Properties;
    6. @Component
    7. public class KaptchaConfig {
    8.     @Bean
    9.     public DefaultKaptcha getDefaultKaptcha(){
    10.         DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
    11. //Properties类
    12.         Properties properties = new Properties();
    13. // 图片边框
    14.         properties.put("kaptcha.border", "no");
    15.         / 边框颜色
    16. properties.put("kaptcha.border.color", "105,179,90");
    17. // 字体颜色
    18. properties.put("kaptcha.textproducer.font.color", "black");
    19.         // 图片宽
    20. properties.put("kaptcha.image.width", "150");
    21.         // 图片高
    22. properties.put("kaptcha.image.height", "40");
    23.         // 字体大小
    24. properties.put("kaptcha.textproducer.font.size", "30");
    25.         // session key
    26. properties.put("kaptcha.session.key", "verifyCode");
    27.         // 验证码长度
    28. properties.put("kaptcha.textproducer.char.space", "5");
    29. // 字体
    30. properties.put("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
    31. //图片干扰
    32. properties.put("kaptcha.noise.impl","com.google.code.kaptcha.impl.DefaultNoise");
    33. //Kaptcha 使用上述配置
    34.         Config config = new Config(properties);
    35.         defaultKaptcha.setConfig(config);
    36.         return defaultKaptcha;
    37.     }
    38. }


    1.3.2 创建后端控制类生成验证码
             创建控制类CommonController类,一方面通过流的方式将随机生成的验证码图片信息发送到前端浏览器;另一方面将验证码中的验证信息写入session中,以方便后续的验证

    1. import com.google.code.kaptcha.impl.DefaultKaptcha;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.web.bind.annotation.GetMapping;
    5. import javax.imageio.ImageIO;
    6. import javax.servlet.ServletOutputStream;
    7. import javax.servlet.http.HttpServletRequest;
    8. import javax.servlet.http.HttpServletResponse;
    9. import java.awt.image.BufferedImage;
    10. import java.io.ByteArrayOutputStream;
    11. @Controller
    12. public class CommonController {
    13.     @Autowired
    14.     private DefaultKaptcha captchaProducer;
    15.     @GetMapping("/common/kaptcha")
    16. public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    17. byte[] captchaOutputStream = null;
    18. ByteArrayOutputStream imgOutputStream = new ByteArrayOutputStream();
    19. try {
    20. //生产验证码字符串并保存到session中
    21. String verifyCode = captchaProducer.createText();
    22. HttpSession session = httpServletRequest.getSession();
    23. session.setAttribute("verifyCode", verifyCode);
    24. session.setMaxInactiveInterval(20);
    25. //单独实现验证码60s过期功能
    26. stringRedisTemplate.opsForValue().set(“mar:captcha:”+session.getId(),capText,60, TimeUnit.SECONDS);
    27. BufferedImage challenge = captchaProducer.createImage(verifyCode);
    28. ImageIO.write(challenge, "jpg", imgOutputStream);
    29. } catch (IllegalArgumentException e) {
    30. httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
    31. return;
    32. }
    33. captchaOutputStream = imgOutputStream.toByteArray();
    34. httpServletResponse.setHeader("Cache-Control", "no-store");
    35. httpServletResponse.setHeader("Pragma", "no-cache");
    36. httpServletResponse.setDateHeader("Expires", 0);
    37. httpServletResponse.setContentType("image/jpeg");
    38. ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
    39. responseOutputStream.write(captchaOutputStream);
    40. responseOutputStream.flush();
    41. responseOutputStream.close();
    42. }
    43. }

    实现验证码的验证与页面跳转
     对前端输入的数据并发送到服务器的验证信息进行校验,当输入信息与验证码信息一致则跳转至success.html页面,否则跳转至false.html页面

    1. @Controller
    2. public class AdminController {
    3.     @PostMapping("/loginh")
    4.     public String loginByKaptcha(@RequestParam("verifyCode") String verifyCode,
    5.                         HttpSession session){
    6.         String kaptchaCode = session.getAttribute("verifyCode") + "";
    7. String sessionYzm = stringRedisTemplate.opsForValue().get(mar:captcha:" + request.getSession().getId());
    8. if (sessionYzm==null){
    9. //返回给前端
    10. return "验证码已过期,请重新输入!";
    11. }
    12.         if(verifyCode.equals(kaptchaCode)){
    13.             return "success";
    14.         }
    15.         return "false";
    16.     }
    17. }

  • 相关阅读:
    Java中的读写锁ReentrantReadWriteLock详解,存在一个小缺陷
    Visual Assist 代码辅助检查和重构
    excel-gen.js 导出excel 功能
    某大厂软件测试岗一面笔试题+二面问答题面试经验分享
    kubernetes--pod详解
    Shell 正则表达式
    【多目标进化优化】MOEA 的分类
    JAVA大学生互动交流论坛计算机毕业设计Mybatis+系统+数据库+调试部署
    C语言——联合与枚举
    C语言-杨辉三角的三种解法-简单易懂篇
  • 原文地址:https://blog.csdn.net/weixin_53998054/article/details/127809345