Verification code generation based on SpringBoot+kaptcha

tutorial

1. Add Kaptcha dependency

Add Kaptcha dependency in the pom.xml file:

<dependency>
    <groupId>com.github.penggle</groupId>
    <artifactId>kaptcha</artifactId>
    <version>2.3.2</version>
</dependency>
<!--或者 都是可以的-->
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>kaptcha</artifactId>
<version>0.0.9</version>
</dependency>

2. Configure Kaptcha parameters

2.1 Add Kaptcha-related configuration in the application.properties file:

# Kaptcha 验证码配置
kaptcha.border=yes
kaptcha.border.color=black
kaptcha.border.thickness=1
kaptcha.textproducer.font.size=30
kaptcha.image.width=120
kaptcha.image.height=40
kaptcha.textproducer.char.space=5
kaptcha.session.key=kaptchaCode
kaptcha.textproducer.char.length=4
kaptcha.textproducer.font.names=Arial, Courier
kaptcha.noise.impl=com.google.code.kaptcha.impl.NoNoise

2.2 Create Kaptcha configuration class

Create a Kaptcha configuration class that is used to configure Kaptcha related parameters and register it as a Spring Bean:

@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha getDefaultKaptcha() {
        // 生成验证码配置
        Properties properties = new Properties();
        properties.setProperty("kaptcha.border", "yes");
        properties.setProperty("kaptcha.border.color", "black");
        properties.setProperty("kaptcha.border.thickness", "1");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        properties.setProperty("kaptcha.image.width", "120");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.textproducer.char.space", "5");
        properties.setProperty("kaptcha.session.key", "kaptchaCode");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.font.names", "Arial,Courier");
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");

        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }

}

3. Create the Controller layer

Create a Controller for generating the verification code image, and put the verification code text into the session:

@RestController
public class KaptchaController {

    @Autowired
    private DefaultKaptcha captchaProducer;

    @RequestMapping("/kaptcha")
    public void kaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 定义响应输出类型为图片格式
        response.setContentType("image/jpeg");

        // 不缓存响应内容
        response.setHeader("Cache-Control", "no-store, no-cache");

        // 获取验证码字符串并将其绑定到 session 中
        String kaptchaText = captchaProducer.createText();
        request.getSession().setAttribute("kaptchaCode", kaptchaText);

        // 生成验证码图片并输出到响应输出流中
        BufferedImage kaptchaImage = captchaProducer.createImage(kaptchaText);
        ServletOutputStream servletOutputStream = response.getOutputStream();
        ImageIO.write(kaptchaImage, "jpg", servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
    }

}

3.1 Display the verification code on the front-end page

Add the following code where the verification code needs to be displayed:

<img src="/kaptcha" alt="验证码" onclick="this.src='/kaptcha?'+Math.random()" />

In this way, after clicking the picture, the verification code picture corresponding to the current URL will be automatically refreshed.

3.2 Verify verification code

In the Controller method that needs to verify the verification code, obtain the saved verification code text through the session, and compare it with the verification code entered by the user:

@PostMapping("/login")
public String login(@RequestParam String username, @RequestParam String password,
@RequestParam("kaptcha")String kaptcha, HttpSession session) {

        // 从 session 中获取验证码文本
        String kaptchaCode = (String)session.getAttribute("kaptchaCode");

        // 判断验证码是否正确
        if (StringUtils.isBlank(kaptcha)
        || StringUtils.isBlank(kaptchaCode)
        || !kaptcha.equals(kaptchaCode)) {
        return "验证码错误,请重新输入!";
        }

        // 验证码正确,继续登录操作...
        }

At this point, Spring Boot's process of implementing verification codes is complete!

In general, the verification code function in Spring Boot can be easily implemented using the Kaptcha toolkit.

4. Demonstration process

4.1 Get verification code

4.2 Verify the verification code correctly

4.3 Error verification verification code

5. perfect

Set the expiration time of the verification code

5.1 Encoding method

Store the current time when storing

session.setAttribute("captchaTime", System.currentTimeMillis());

When using it, compare the current time with the time when it was stored.

@RequestMapping("/verify")
public String verify(HttpServletRequest request, String captcha) {
        // 从 session 中获取验证码值和过期时间信息
        HttpSession session = request.getSession();
        String sessionCaptcha = (String) session.getAttribute("captcha");
        String[] parts = sessionCaptcha.split(":");
        String sessionCaptchaValue = parts[0];
        long sessionExpireTime = Long.parseLong(parts[1]);

        // 比较验证码的值和过期时间
        if (captcha.equalsIgnoreCase(sessionCaptchaValue)
        && System.currentTimeMillis() < sessionExpireTime) {
        // 验证码正确且未过期,执行相应的业务逻辑
        // ...

        return "success"; // 跳转到成功页面
        } else {
        // 验证码错误或已过期,返回错误信息
        // ...

        return "error"; // 跳转到错误页面
        }
        }

Expired prompt information. 

Guess you like

Origin blog.csdn.net/weixin_41957626/article/details/131314352