SpringBoot使用 easy-captcha 实现验证码登录功能

发布于:2025-02-10 ⋅ 阅读:(25) ⋅ 点赞:(0)


在前后端分离的项目中,登录功能是必不可少的。为了提高安全性,通常会加入验证码验证。 easy-captcha 是一个简单易用的验证码生成库,支持多种类型的验证码(如字符、中文、算术等)。本文将介绍如何在 Spring Boot 后端和 Vue.js 前端中集成 easy-captcha,实现验证码登录功能。

一、 环境准备

1. 解决思路

  1. 后端使用 easy-captcha 创建验证码对象。
  2. 将验证码文本存储到 Redis 中,并生成一个随机的 key。
  3. 将验证码的 Base64 字符串和 key 返回给前端。
  4. 前端通过 Base64 字符串显示验证码图片,并将 key 保存起来。
  5. 登录时,前端将用户输入的验证码和 key 发送到后端。
  6. 后端通过 key 从 Redis 中获取验证码文本,并进行比对验证。

2. 接口文档

URL

GET /captcha

参数

返回

{
    "msg": "操作成功",
    "code": 200,
    "data": {
      "uuid": "b71fafb1a91b4961afb27372bd3af77c",
      "captcha": "data:image/png;base64,iVBORw0KGgoAAAA",
      "code": "nrew"
    }
}

3. redis下载

redis安装配置教程

二、后端实现

1. 引入依赖

在 pom.xml 文件中引入 easy-captchaRedis 相关依赖:

<dependency>
    <groupId>com.github.whvcse</groupId>
    <artifactId>easy-captcha</artifactId>
    <version>1.6.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. 添加配置

application.yml里添加连接redis数据库的配置信息:

spring:
  redis:
    open: true
    database: 1
    host: localhost
    port: 6379

3. 后端代码实现

controller:

@RestController
public class LoginController {

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/captcha")
	public Result captcha() {
	    // 创建一个 SpecCaptcha 对象,设置验证码图片的宽度、高度和字符长度
	    SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
	
	    // 生成验证码文本,并将其转换为小写(方便后续比较,忽略大小写)
	    String code = specCaptcha.text().toLowerCase();
	
	    // 生成一个唯一的 UUID,用于存储验证码到 Redis 中
	    String uuid = IdUtil.simpleUUID();
	
	    // 将验证码文本存入 Redis,并设置过期时间为 2 分钟(120 秒)
	    // 这样可以确保验证码在一定时间后自动失效,避免被恶意利用
	    this.redisTemplate.opsForValue().set(uuid, code, 120, TimeUnit.SECONDS);
	
	    // 创建一个 Map,用于存储返回给前端的数据
	    Map<String, String> map = new HashMap<String, String>(3);
	
	    // 将 UUID 存入 Map,前端需要将这个 UUID 一起发送到后端进行验证
	    map.put("uuid", uuid);
	
	    // 将生成的验证码文本存入 Map(可选,通常前端不需要知道验证码文本)
	    map.put("code", code);
	
	    // 将验证码图片转换为 Base64 字符串,并存入 Map
	    // 前端可以通过这个 Base64 字符串生成验证码图片
	    map.put("captcha", specCaptcha.toBase64());
	
	    // 返回 Result 对象,其中包含验证码图片的 Base64 字符串和 UUID
	    // Result.ok() 表示操作成功,put("data", map) 将 Map 数据放入响应中
	    return Result.ok().put("data", map);
	}
	@PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm, HttpSession session){
        //验证码校验
        String code = (String) this.redisTemplate.opsForValue().get(loginForm.getUuid());
        //判断验证码是否有效
        if(code == null){
            return Result.error("验证码已过期");
        }
        //判断验证码是否正确
        if(!code.equals(loginForm.getCaptcha())){
            return Result.error("验证码错误");
        }
        //判断用户名是否正确
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginForm.getUsername());
        User user = this.userService.getOne(queryWrapper);
        if(user == null){
            return Result.error("用户名错误");
        }
        //判断密码是否正确
        String password = SecureUtil.sha256(loginForm.getPassword());
        if(!password.equals(user.getPassword())){
            return Result.error("密码错误");
        }
        //验证用户是否可用
        if(user.getStatus() == 0) {
            return Result.error("账号已被锁定,请联系管理员");
        }
        //登录成功
        session.setAttribute("user", user);
        //创建token
        String token = this.jwtUtil.createToken(String.valueOf(user.getUserId()));
        this.redisTemplate.opsForValue().set("communityuser-"+user.getUserId(), token,jwtUtil.getExpire());
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", jwtUtil.getExpire());
        LogAspect.user = user;
        return Result.ok().put("data", map);
    }
}

RedisTemplate 是 Spring Data Redis 提供的一个高级抽象,封装了 Redis 的操作。它支持多种数据结构(如字符串、列表、集合、哈希等),并提供了丰富的操作方法。通过 RedisTemplate,可以方便地执行 Redis 命令,而无需直接使用 Redis 的原生客户端。

常用方法

  • opsForValue():用于操作 Redis 中的字符串(String)数据。
  • opsForList():用于操作 Redis 中的列表(List)数据。
  • opsForSet():用于操作 Redis 中的集合(Set)数据。
  • opsForHash():用于操作 Redis 中的哈希(Hash)数据。
  • opsForZSet():用于操作 Redis 中的有序集合(Sorted Set)数据。

4. 前端代码实现

  1. 获取验证码
    前端通过调用后端接口获取验证码图片和 UUID。这个 UUID 用于在后端标识验证码的唯一性。
// 获取验证码
getCaptcha() {
  getCaptchaImg().then(res => {
    this.captchaPath = res.data.captcha; // 将验证码图片的 Base64 字符串赋值给 captchaPath
    this.loginForm.uuid = res.data.uuid; // 将 UUID 赋值给 loginForm 的 uuid 属性
    if (process.env.NODE_ENV === 'development') {
      this.loginForm.captcha = res.data.code; // 在开发环境中自动填充验证码(方便测试)
    }
  });
}
  1. 显示验证码
    前端通过 el-image 组件显示验证码图片,并提供点击刷新功能。
<el-image
  class="captcha-img"
  :src="captchaPath" <!-- 绑定验证码图片的 Base64 字符串 -->
  @click="getCaptcha()" <!-- 点击图片时重新获取验证码 -->
/>

3. 提交表单时验证验证码
用户输入验证码后,点击登录按钮提交表单。前端将用户输入的验证码和 UUID 一起发送到后端进行验证。

handleLogin() {
  this.$refs.loginForm.validate(valid => {
    if (valid) {
      this.loading = true;
      this.$store.dispatch('user/login', this.loginForm)
        .then(() => {
          this.$router.push({ path: this.redirect || '/' }); // 登录成功后跳转
        })
        .catch(() => {
          this.getCaptcha(); // 登录失败,重新获取验证码
          this.loading = false;
        });
    } else {
      return false;
    }
  });
}

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到