SpringBoot整合EasyCaptcha图形验证码

简介

EasyCaptcha:https://github.com/ele-admin/EasyCaptcha

Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。

添加依赖

<dependency>
    <groupId>com.github.whvcse</groupId>
    <artifactId>easy-captcha</artifactId>
    <version>1.6.2</version>
</dependency>

需求分析

前后端分离,前端使用 Vue3 开发,后端使用 Spring Boot 开发。组件首次挂载时,获取验证码。点击图片刷新获取验证码,验证码存储到 Redis 数据库中。

代码实现

前端

api

/**
 * 后端响应的验证码参数格式
 */
export interface CaptchaResponse {
  /**
   * redis中的验证码缓存key
   */
  captchaKey: string;
  /**
   * 验证码图片Base64字符串
   */
  captchaBase64: string;
}

/**
 * 获取验证码api
 */
export function getCaptchaApi(): AxiosPromise<CaptchaResponse> {
  return request({
    url: '/auth/captcha',
    method: 'get'
  })
}

vue组件

<el-form-item prop="verCode">
  <el-input placeholder="验证码" size="large" style="width: 67%;" :prefix-icon="Aim" v-model="loginForm.verCode">
  </el-input>
  <div class="login-code">
    <el-image :src="captchaResponse.captchaBase64" style="height: 38px;" @click="getCaptcha" title="刷新图片验证码">
      <template #error>
        <div class="image-slot">
          <el-icon color="#A1A4AB"><icon-picture /></el-icon>
        </div>
      </template>
    </el-image>
  </div>
</el-form-item>

<script setup lang='ts'>
/**
 * 后端响应的验证码参数
 */
const captchaResponse = ref<CaptchaResponse>({
  captchaKey: '', // redis中的验证码缓存key
  captchaBase64: '', // 验证码图片Base64字符串
})
/**
 * 获取图片验证码
 */
function getCaptcha() {
  getCaptchaApi().then((response) => {
    captchaResponse.value = response.data
  }).catch((error) => {
    return Promise.reject(error)
  })
}
/**
 * 组件挂载时,获取图片验证码
 */
onMounted(() => {
  getCaptcha()

})
</script>

后端

package com.lcloud.controller;

import com.lcloud.dto.UserLoginDTO;
import com.lcloud.response.Response;
import com.lcloud.service.AuthService;
import com.lcloud.vo.CaptchaVO;
import com.lcloud.vo.UserLoginVO;
import com.wf.captcha.SpecCaptcha;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/auth")
@Tag(name = "授权管理")
public class AuthController {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取图片验证码
     *
     * @return 图片验证码的key和base64编码字符串
     * @throws Exception 抛出异常
     */
    @GetMapping("/captcha")
    @Operation(summary = "获取图片验证码")
    public Response<CaptchaVO> captcha() throws Exception {
        // 设置图片验证码的属性(宽、高、长度、字体)
        SpecCaptcha specCaptcha = new SpecCaptcha(100, 38, 4);
        specCaptcha.setFont(1);
        // 图片验证码转换成base64编码字符串
        String captchaBase64 = specCaptcha.toBase64();
        // 图片验证码结果
        String key = UUID.randomUUID().toString();
        //log.info("key: {}", key);
        String verCode = specCaptcha.text().toLowerCase();
        // (key,value)=》(uuid,verCode)存入redis
        redisTemplate.opsForValue().set(key, verCode);
        // 返回图片验证码的key和base64编码字符串
        CaptchaVO captchaVO = CaptchaVO.builder().captchaKey(key).captchaBase64(captchaBase64).build();
        return Response.success(captchaVO);
    }
}

测试

image-20240125212212926

image-20240125212310817

Spring Boot和Vue集成的应用中,将图形验证码缓存到Redis是一个常见做法,可以提高系统的安全性和效率。这里会涉及到几个步骤: 1. 生成图形验证码:首先,需要在服务器端生成一个图形验证码。这通常通过一些图形验证码库完成,比如kaptcha、Simple-Captcha等。 2. 缓存验证码:生成的验证码需要与一个唯一标识(比如随机数字符串)一起存入Redis。这个唯一标识会被发送到前端,用户在提交表单时需要输入这个验证码。 3. 验证码验证:当用户提交表单时,带上图形验证码的唯一标识和用户输入的验证码值。服务器端接收到这些数据后,会去Redis中查找与唯一标识对应的验证码值,然后与用户输入的值进行对比。如果一致,说明验证通过,否则验证失败。 4. 清除缓存:一旦验证码验证通过,就应该从Redis中删除对应的验证码信息,避免重复使用。如果用户提交的验证码在有效期内没有被验证,也应该清除缓存,防止内存泄漏。 以下是一个简单的代码示例(伪代码): ```java // 生成验证码并保存到Redis String captchaId = generateUniqueCaptchaId(); String captchaText = generateCaptchaImage(captchaId); // 生成图形验证码 redisTemplate.opsForValue().set(CAPTCHA_KEY_PREFIX + captchaId, captchaText, captchaTimeout, TimeUnit.SECONDS); // 存入Redis // 验证码验证 String inputCaptchaId = userInput.getCaptchaId(); String inputCaptchaText = userInput.getCaptchaText(); String realCaptchaText = redisTemplate.opsForValue().get(CAPTCHA_KEY_PREFIX + inputCaptchaId); boolean isValid = realCaptchaText != null && realCaptchaText.equals(inputCaptchaText); if (isValid) { redisTemplate.delete(CAPTCHA_KEY_PREFIX + inputCaptchaId); // 验证成功,清除缓存 // 处理业务逻辑 } else { // 验证失败处理 } ``` 在实际操作中,还需要考虑验证码的生成和存储的安全性,比如使用HTTPS传输验证码标识,以及合理的验证码过期时间等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值