SpringBoot使用easy-captcha 实现验证码登录功能(解决思路)
作者:八月五
文章介绍了如何使用Spring Boot和Easy-Captcha实现验证码登录功能,后端通过Easy-Captcha生成验证码并存储在Redis中,前端获取验证码并显示给用户,登录时,前端将用户输入的验证码和标识符发送到后端进行验证,感兴趣的朋友跟随小编一起看看吧
一、 环境准备
1. 解决思路
- 后端使用 easy-captcha 创建验证码对象。
- 将验证码文本存储到 Redis 中,并生成一个随机的 key。
- 将验证码的 Base64 字符串和 key 返回给前端。
- 前端通过 Base64 字符串显示验证码图片,并将 key 保存起来。
- 登录时,前端将用户输入的验证码和 key 发送到后端。
- 后端通过 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-captcha
和 Redis
相关依赖:
<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. 前端代码实现
获取验证码
前端通过调用后端接口获取验证码图片和 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; // 在开发环境中自动填充验证码(方便测试) } }); }
显示验证码
前端通过 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; } }); }
到此这篇关于SpringBoot使用 easy-captcha 实现验证码登录功能的文章就介绍到这了,更多相关SpringBoot验证码登录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!