侧边栏壁纸
博主头像
拾荒的小海螺博主等级

只有想不到的,没有做不到的

  • 累计撰写 140 篇文章
  • 累计创建 15 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

JAVA:Spring Boot整合Kaptcha验证码实现登录验证

拾荒的小海螺
2024-05-07 / 0 评论 / 0 点赞 / 10 阅读 / 5490 字

1、简述

在Web应用程序中,验证码是一种常见的安全措施,用于验证用户的身份以防止恶意活动,如自动化攻击或机器人。Spring Boot提供了许多库和工具,使得集成验证码变得相对容易。在本文中,我们将介绍如何使用Kaptcha库在Spring Boot应用程序中实现验证码功能。

1715044583283.jpg

2、集成

Kaptcha是一个用Java编写的简单验证码生成库。它可以生成基于文本的验证码图片,用于Web应用程序的身份验证。Kaptcha提供了许多配置选项,使得生成的验证码图片可以适应各种应用场景。

2.1 添加依赖

首先,我们需要在Spring Boot项目中添加Kaptcha的依赖。在pom.xml文件中添加以下依赖:

<dependency>
    <groupId>com.github.axet</groupId>
    <artifactId>kaptcha</artifactId>
    <version>0.0.9</version>
</dependency>

2.2 配置

接下来,我们需要配置Kaptcha以生成验证码图片。在Spring Boot中,我们可以通过创建一个配置类来完成这项任务。创建一个名为KaptchaConfig的类,并将以下内容添加到其中:

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

@Configuration
public class KaptchaConfig {

    @Bean
    public DefaultKaptcha producer() {
        Properties properties = new Properties();
        properties.put("kaptcha.border", "no");
        properties.put("kaptcha.textproducer.font.color", "black");
        properties.put("kaptcha.textproducer.char.space", "5");
        properties.put("kaptcha.textproducer.font.names", "Arial,Courier,cmr10,宋体,楷体,微软雅黑");
        // 配置验证码图片的宽度
        properties.setProperty("kaptcha.image.width", "150");
        // 配置验证码图片的高度
        properties.setProperty("kaptcha.image.height", "50");
        // 配置验证码字符长度
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;
    }
}

在上面的配置中,我们设置了验证码图片的宽度、高度和字符长度。你可以根据自己的需求进行调整。

3、创建验证码接口

现在,我们需要创建一个接口来生成和提供验证码图片。我们将创建一个RESTful接口,让客户端可以通过HTTP请求获取验证码图片:

@GetMapping("captcha.jpg")
public void captcha(HttpServletResponse response, String uuid)throws IOException {
	response.setHeader("Cache-Control", "no-store, no-cache");
	response.setContentType("image/jpeg");

	//获取图片验证码
	BufferedImage image = sysCaptchaService.getCaptcha(uuid);

	ServletOutputStream out = response.getOutputStream();
	ImageIO.write(image, "jpg", out);
	IOUtils.closeQuietly(out);
}

以一个随机的UUID来设计当前随机验证码存库表,通过当前库表的过期时间来校验:

@Data
@TableName("lk_captcha")
public class CaptchaEntity  {
    @TableId(type = IdType.INPUT)
    private String uuid;
    /**
     * 验证码
     */
    private String code;
    /**
     * 过期时间
     */
    private Date expireTime;

}

创建service时间接口来获取当前随机的图片流和校验接口:

@Autowired
  private Producer producer;

  @Override
  public BufferedImage getCaptcha(String uuid) {
      if(StringUtils.isBlank(uuid)){
          throw new RRException("uuid不能为空");
      }
      //生成文字验证码
      String code = producer.createText();

      CaptchaEntity  captchaEntity = new CaptchaEntity ();
      captchaEntity.setUuid(uuid);
      captchaEntity.setCode(code);
      //5分钟后过期
      captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
      this.save(captchaEntity);

      return producer.createImage(code);
  }

  @Override
  public boolean validate(String uuid, String code) {
      CaptchaEntity captchaEntity = this.getOne(new QueryWrapper<CaptchaEntity >().eq("uuid", uuid));
      if(captchaEntity == null){
          return false;
      }

      //删除验证码
      this.removeById(uuid);

      if(captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()){
          return true;
      }

      return false;
  }

在上面的代码中,我们创建了一个名为getCaptcha的处理方法,它将生成验证码图片,并将图片以BufferedImage的形式返回给客户端。

4、结论

通过使用Kaptcha库,我们可以很容易地在Spring Boot项目中实现验证码功能,增强Web应用程序的安全性。在本文中,我们介绍了如何添加Kaptcha依赖、配置Kaptcha、创建验证码接口,并集成验证码功能到Spring Boot应用程序中。

希望本文能够帮助你顺利地在你的项目中实现验证码功能!

0

评论区