一、后端实现
图片验证码都需要短时有效的,所以把验证码放到Redis中是不错的选择。
1.1 定义返回实体类对象:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class CaptchaImageRespVO {
@ApiModelProperty(value = "是否开启", required = true, example = "true", notes = "如果为 false,则关闭验证码功能")
private Boolean enable;
@ApiModelProperty(value = "uuid", example = "1b3b7d00-83a8-4638-9e37-d67011855968",
notes = "enable = true 时,非空!通过该 uuid 作为该验证码的标识")
private String uuid;
@ApiModelProperty(value = "图片", notes = "enable = true 时,非空!验证码的图片内容,使用 Base64 编码")
private String img;
}
1.2 获取验证码接口实现
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
@Resource
private StringRedisTemplate stringRedisTemplate;
@Override
public CaptchaImageRespVO getImage() {
CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(160, 60);
CaptchaImageRespVO respVO = new CaptchaImageRespVO();
respVO.setEnable(true);
// 获得图片的Base64形式
respVO.setImg(circleCaptcha.getImageBase64());
String uuid = IdUtil.fastSimpleUUID();
// 键 uuid,值 code,过期时间5分钟
stringRedisTemplate.opsForValue().set(uuid, circleCaptcha.getCode(),5, TimeUnit.MINUTES);
return respVO;
}
1.3 登录逻辑
// 判断验证码是否正确,如果正确,要删除redis中的验证码
// 使用账号密码,进行登录
// 缓存登陆用户到 Redis 中,返回 sessionId 编号
二、前端实现
// 获取验证码
export function getCodeImg() {
return request({
url: '/system/captcha/get-image',
method: 'get',
timeout: 20000
})
}
"data:image/gif;base64," + res.img
getCode() {
// 只有开启的状态,才加载验证码。默认开启
if (!this.captchaEnable) {
return;
}
// 请求远程,获得验证码
getCodeImg().then((res) => {
res = res.data;
this.captchaEnable = res.enable;
if (this.captchaEnable) {
this.codeUrl = "data:image/gif;base64," + res.img;
this.loginForm.uuid = res.uuid;
}
});
},
<div class="login-code">
<img :src="codeUrl" @click="getCode" class="login-code-img" />
</div>