EasyCaptcha:https://github.com/ele-admin/EasyCaptcha
Java图形验证码,支持gif、中文、算术等类型,可用于Java Web、JavaSE等项目。
com.github.whvcse easy-captcha 1.6.2
前后端分离,前端使用 Vue3 开发,后端使用 Spring Boot 开发。组件首次挂载时,获取验证码。点击图片刷新获取验证码,验证码存储到 Redis 数据库中。
/**
* 后端响应的验证码参数格式
*/
export interface CaptchaResponse {
/**
* redis中的验证码缓存key
*/
captchaKey: string;
/**
* 验证码图片Base64字符串
*/
captchaBase64: string;
}
/** * 获取验证码api */ export function getCaptchaApi(): AxiosPromise{ return request({ url: '/auth/captcha', method: 'get' }) }
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 redisTemplate;
/**
* 获取图片验证码
*
* @return 图片验证码的key和base64编码字符串
* @throws Exception 抛出异常
*/
@GetMapping("/captcha")
@Operation(summary = "获取图片验证码")
public Response 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);
}
}

