Spring Boot 3 整合 Hutool 验证码实战

2023-12-18 06:11:03

🚀 作者主页: 有来技术
🔥 开源项目: youlai-mall 🍃 vue3-element-admin 🍃 youlai-boot
🌺 仓库主页: Gitee 💫 Github 💫 GitCode
💖 欢迎点赞 👍 收藏 ?留言 📝 如有错误敬请纠正!

前言

在Web应用开发中,验证码是一种常用的安全措施,用于防止恶意软件自动提交表单。SpringBoot作为一种流行的Java企业级应用框架,提供了快速开发的能力。Hutool作为一个全面的Java工具类库,其中包含了方便的验证码生成工具。本文将指导你如何在SpringBoot 3项目中利用Hutool生成和验证验证码,从而提高应用的安全性和用户体验。

添加依赖

pom.xml中添加Hutool的依赖。Hutool是一个Java工具类库,它提供了简单易用的API,用于处理常见的编码任务,包括生成验证码。

  <dependency>
      <groupId>cn.hutool</groupId>
      <artifactId>hutool-all</artifactId>
      <version>5.8.23</version>
  </dependency>

验证码配置

application.yml

配置 Hutool 验证码类型、尺寸、字体和有效期

# 验证码配置
captcha:
  # 验证码类型 circle-圆圈干扰验证码|gif-Gif验证码|line-干扰线验证码|shear-扭曲干扰验证码
  type: circle
  # 验证码宽度
  width: 120
  # 验证码高度
  height: 40
  # 验证码干扰元素个数
  interfere-count: 2
  # 文本透明度(0.0-1.0)
  text-alpha: 0.8
  # 验证码字符配置
  code:
    # 验证码字符类型 math-算术|random-随机字符
    type: math
    # 验证码字符长度,type=算术时,表示运算位数(1:个位数运算 2:十位数运算);type=随机字符时,表示字符个数
    length: 1
  # 验证码字体
  font:
    # 字体名称 Dialog|DialogInput|Monospaced|Serif|SansSerif
    name: SansSerif
    # 字体样式 0-普通|1-粗体|2-斜体
    weight: 1
    # 字体大小
    size: 30
  # 验证码有效期(秒)
  expire-seconds: 120

CaptchaProperties.java

新建 CaptchaProperties.java 配置类将 application.yml 映射为 Java 对象

package com.youlai.system.plugin.captcha;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 验证码配置
 *
 * @author haoxr
 * @since 2023/11/24
 */
@Component
@ConfigurationProperties(prefix = "captcha")
@Data
public class CaptchaProperties {

    /**
     * 验证码类型  circle-圆圈干扰验证码|gif-Gif验证码|line-干扰线验证码|shear-扭曲干扰验证码
     */
    private String type;

    /**
     * 验证码图片宽度
     */
    private int width;
    /**
     * 验证码图片高度
     */
    private int height;

    /**
     * 干扰线数量
     */
    private int interfereCount;

    /**
     * 文本透明度
     */
    private Float textAlpha;

    /**
     * 验证码过期时间,单位:秒
     */
    private Long expireSeconds;

    /**
     * 验证码字符配置
     */
    private CodeProperties code;

    /**
     * 验证码字体
     */
    private FontProperties font;

    /**
     * 验证码字符配置
     */
    @Data
    public static class CodeProperties {
        /**
         * 验证码字符类型 math-算术|random-随机字符串
         */
        private String type;
        /**
         * 验证码字符长度,type=算术时,表示运算位数(1:个位数 2:十位数);type=随机字符时,表示字符个数
         */
        private int length;
    }

    /**
     * 验证码字体配置
     */
    @Data
    public static class FontProperties {
        /**
         * 字体名称
         */
        private String name;
        /**
         * 字体样式  0-普通|1-粗体|2-斜体
         */
        private int weight;
        /**
         * 字体大小
         */
        private int size;
    }
}

CaptchaConfig.java

新建自动装配配置类 CaptchaConfig.java,用于注入验证码生成器CodeGenerator 和验证码字体Font`,保证全局唯一示例。

package com.youlai.system.plugin.captcha;

import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.captcha.generator.RandomGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.awt.*;

/**
 * 验证码自动装配配置
 *
 * @author haoxr
 * @since 2023/11/24
 */
@Configuration
public class CaptchaConfig {

    @Autowired
    private CaptchaProperties captchaProperties;

    /**
     * 验证码文字生成器
     *
     * @return CodeGenerator
     */
    @Bean
    public CodeGenerator codeGenerator() {
        String codeType = captchaProperties.getCode().getType();
        int codeLength = captchaProperties.getCode().getLength();
        if ("math".equalsIgnoreCase(codeType)) {
            return new MathGenerator(codeLength);
        } else if ("random".equalsIgnoreCase(codeType)) {
            return new RandomGenerator(codeLength);
        } else {
            throw new IllegalArgumentException("Invalid captcha generator type: " + codeType);
        }
    }

    /**
     * 验证码字体
     */
    @Bean
    public Font captchaFont() {
        String fontName = captchaProperties.getFont().getName();
        int fontSize = captchaProperties.getFont().getSize();
        int fontWight = captchaProperties.getFont().getWeight();
        return new Font(fontName, fontWight, fontSize);
    }


}

验证码服务类

下面贴出部分关键代码,完整代码:youlaii-boot

package com.youlai.system.service.impl;

// ...

/**
 * 认证服务实现类
 *
 * @author haoxr
 * @since 2.4.0
 */
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final CodeGenerator codeGenerator;
    private final Font captchaFont;
    private final CaptchaProperties captchaProperties;

    /**
     * 获取验证码
     *
     * @return 验证码
     */
    @Override
    public CaptchaResult getCaptcha() {

        String type = captchaProperties.getType();
        int width = captchaProperties.getWidth();
        int height = captchaProperties.getHeight();
        int interfereCount = captchaProperties.getInterfereCount();
        int codeLength = captchaProperties.getCode().getLength();

        AbstractCaptcha captcha;
        if ("circle".equalsIgnoreCase(type)) {
            captcha = CaptchaUtil.createCircleCaptcha(width, height, codeLength, interfereCount);
        } else if ("gif".equalsIgnoreCase(type)) {
            captcha = CaptchaUtil.createGifCaptcha(width, height, codeLength);
        } else if ("line".equalsIgnoreCase(type)) {
            captcha = CaptchaUtil.createLineCaptcha(width, height, codeLength, interfereCount);
        } else if ("shear".equalsIgnoreCase(type)) {
            captcha = CaptchaUtil.createShearCaptcha(width, height, codeLength, interfereCount);
        } else {
            throw new IllegalArgumentException("Invalid captcha type: " + type);
        }
        captcha.setGenerator(codeGenerator);
        captcha.setTextAlpha(captchaProperties.getTextAlpha());
        captcha.setFont(captchaFont);

        String captchaCode = captcha.getCode();
        String imageBase64Data = captcha.getImageBase64Data();

        // 验证码文本缓存至Redis,用于登录校验
        String captchaKey = IdUtil.fastSimpleUUID();
        redisTemplate.opsForValue().set(CacheConstants.CAPTCHA_CODE_PREFIX + captchaKey,captchaCode,
                captchaProperties.getExpireSeconds(), TimeUnit.SECONDS);

        return CaptchaResult.builder()
                .captchaKey(captchaKey)
                .captchaBase64(imageBase64Data)
                .build();
    }

}

验证码接口

下面贴出部分关键代码,完整代码:youlaii-boot

   @Operation(summary = "获取验证码")
    @GetMapping("/captcha")
    public Result<CaptchaResult> getCaptcha() {
        CaptchaResult captcha = authService.getCaptcha();
        return Result.success(captcha);
    }

验证码测试

f访问接口 http://ip:port/api/v1/auth/captcha 获取验证码如下图:
在这里插入图片描述

结语

通过本文的指南,你应该能够在SpringBoot 3应用中成功整合Hutool来处理验证码相关的需求。这种集成不仅加强了应用的安全性,而且通过为用户提供图形验证码,增强了整体的用户交互体验。

开源项目

  • SpringCloud + Vue3 微服务商城
GithubGitee
后端youlai-mall 🍃youlai-mall 🍃
前端mall-admin🌺mall-admin 🌺
移动端mall-app 🍌mall-app 🍌
  • SpringBoot 3+ Vue3 单体权限管理系统
GithubGitee
后端youlai-boot 🍃youlai-boot 🍃
前端vue3-element-admin 🌺vue3-element-admin 🌺

文章来源:https://blog.csdn.net/u013737132/article/details/135051202
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。