本文章基于vue+element-ui+springboot+redis讲解,其他的都是工具,可以直接拿来用,不懂redis没关系(因为本文只用了简单的存取),但前面三个要懂
如果你只想看前端或者后端的代码逻辑,本文章同样适用
进入页面之后,就会向后端发起一个请求,这个请求会传递最重要的两个值,一个是图片的的字节码的编码(这个不用解释撒,就是用java画一个验证码的图再转成字节码编码,进行传输,然后传给前端解析成图片),一个是存入缓存(redis)的key值(key值为uuid,value为验证码答案)(先记着,后面会讲)
登录后会向后端传四个参数,用户名、密码、code(就是验证码答案)、uuid(redis存的值(key值为uuid,value为验证码答案),取出来之后会跟code做比较,一样的话就说明是你填的验证码对的,允许登录,反之阻止)
{
"code": 100200,
"msg": "返回成功",
"data": {
"img": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAA8AKADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU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Ho7K6hEqjkg9jUdt4Mtop9yWm4543ksB+Br1jTNDSGEKyitKPSIFOdgrgePxLcrTa5m20m0nfyK5V2OT8P6TLAV3LgDtium1G3P2MgDnFakVqkY4UCnXEAkjK4rkKPAymr6V4zjhttOZtMEisyW1vwUPBJIH3hyevavedMhSOBdo7VgtopF3vA710tnEY4gDXVicSq6h7iTSs2uvm/PzJSsWwKeKaKeK5Shwqrq//ACBL/wD69pP/AEE1bFVdX/5Al/8A9e0n/oJqZfCyZfCzkrL/AI8rf/rmv8qsiuZi1q5iiSNUiIRQoyD2/GpP7fuv+ecP/fJ/xrKNaNkZxqxsjpRTgK5n/hIbv/nnB/3yf8aX/hIrv/nnB/3yf8ar20R+2idPsB6ilWJR2Fcx/wAJJef88oP++T/jS/8ACS3n/PKD/vk/40e2iHtonVqMVIK5H/hJ73/nlb/98t/jS/8ACUXv/PK3/wC+W/xo9tEPbROtMYbqKFt0BztFcn/wlV9/zyt/++W/xpf+Ervv+eVt/wB8t/jR7aIe2idkqgVIK4r/AIS2/wD+eNt/3y3+NL/wl+of88bb/vlv/iqPbRD20TthTwM1w/8AwmGof88bX/vlv/iqX/hMtR/542v/AHy3/wAVR7aIe2idwIx6VIoxXCf8JnqP/PG1/wC+G/8AiqX/AITXUv8Anhaf98N/8VR7aIe2id6KeK4D/hNtS/54Wn/fDf8AxVL/AMJxqf8AzwtP++G/+Ko9tEPbRPQRVXV/+QHqH/XtJ/6Ca4r/AITnU/8Anhaf98N/8VUdz4z1G6tZrd4bUJKjIxVWyARjj5qmVaNmKVWNmf/Z",
"uuid": "b9bfa12b336d4e24a82e3c4bae3c6d5f"
}
}
前端逻辑很简单,就是先访问后端,拿到验证码图片后,在验证码框填好,再一起传给登录的后端接口,由后端做判断
// 这里是 element-ui 的 form 子键
// 这是我验证码前面的那个 svg 矢量图
// 这个是验证码框框
// 这个就是旁边的验证码了
// codeUrl 图片做绑定
export function getCodeImg() {
return request({
url: '/fix/user/captchaImage',
method: 'get',
timeout: 20000
})
}
<dependency>
<groupId>com.github.pengglegroupId>
<artifactId>kaptchaartifactId>
<version>2.3.2version>
dependency>
SpringBoot的JSON工具类(java),用于前后端分离_我认不到你的博客-CSDN博客
Redis工具类(redisTemplate)以及 redisTemplate 的用法_我认不到你的博客-CSDN博客_redistemplate sadd
// 字母类验证码 这个和下面那个 我后续会发代码出来
@Resource(name = "captchaProducer")
private Producer captchaProducer;
// 数字类验证码
@Resource(name = "captchaProducerMath")
private Producer captchaProducerMath;
// 在配置文件中取出 这个值是用来 判断生成字母验证码还是数字验证码(加减乘除),我的值为 "math" 就是生成数字验证码
@Value("${validation.captchaType}")
private String captchaType;
// time的值为2,用于设置redis超时时间
@Value("${validation.expiration-time}")
private Integer time;
// redisUtil 是 我封装的redis工具类,上面自取
@Autowired
RedisUtil redisUtil;
// R 是我 自己封装、用于传输json的类,上面连接,可以去看
@Override
public R captchaImage(HttpServletResponse response) {
// 保存验证码信息
// 随机生成UUID
String uuid = UUID.randomUUID().toString();
// 用于存入 redis 的 key 值,由两部分拼接而成
String verifyKey = "captcha_codes:" + uuid;
String capStr = null, code = null;
BufferedImage image = null;
// 生成数字验证码
if ("math".equals(captchaType))
{
// 生成 验证码的 数字信息 比如生成: 1+5=?@6 ,如:5/1=?@5
// 这个生成的就是 可以用 @ 分开前面的 验证码内容 与后面的 验证码答案
String capText = captchaProducerMath.createText();
// 这个用于生成 验证码
capStr = capText.substring(0, capText.lastIndexOf("@"));
// 这个用于生成 验证码答案 存入 redis 中
code = capText.substring(capText.lastIndexOf("@") + 1);
// 生成验证码图片
image = captchaProducerMath.createImage(capStr);
}
// 生成字母验证码
else if ("char".equals(captchaType))
{
// 随机生成字母验证码
capStr = code = captchaProducer.createText();
// 生成验证码图片
image = captchaProducer.createImage(capStr);
}
// 两分钟的验证码
// redisUtil 是 我封装的redis工具类,上面链接自取
// 用于存 验证码的 密码
redisUtil.set(verifyKey, code, time, TimeUnit.MINUTES);
// 转换流信息写出
FastByteArrayOutputStream os = new FastByteArrayOutputStream();
try
{
assert image != null;
// 图片写进流里面
ImageIO.write(image, "jpg", os);
}
catch (IOException e)
{
return R.Failed(e.getMessage());
}
HashMap<String , Object > map = new HashMap<>();
// 转成64位字节码编码 赋值给 img
map.put("img", Base64.encode(os.toByteArray()));
map.put("uuid", uuid);
return R.Success(map);
}
/**
* 验证码配置
*
* @author ruoyi
*/
@Configuration
public class CaptchaConfig
{
/**
* 字母验证码
* @return DefaultKaptcha
*/
@Bean(name = "captchaProducer")
public DefaultKaptcha getKaptchaBean()
{
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 是否有边框 默认为true 我们可以自己设置yes,no
properties.setProperty(KAPTCHA_BORDER, "yes");
// 验证码文本字符颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "black");
// 验证码图片宽度 默认为200
properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
// 验证码图片高度 默认为50
properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
// 验证码文本字符大小 默认为40
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "38");
// KAPTCHA_SESSION_KEY
properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCode");
// 验证码文本字符长度 默认为5
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "4");
// 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
// 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
/**
* 数字验证码
* @return DefaultKaptcha
*/
@Bean(name = "captchaProducerMath")
public DefaultKaptcha getKaptchaBeanMath()
{
DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
Properties properties = new Properties();
// 是否有边框 默认为true 我们可以自己设置yes,no
properties.setProperty(KAPTCHA_BORDER, "yes");
// 边框颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_BORDER_COLOR, "105,179,90");
// 验证码文本字符颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_COLOR, "blue");
// 验证码图片宽度 默认为200
properties.setProperty(KAPTCHA_IMAGE_WIDTH, "160");
// 验证码图片高度 默认为50
properties.setProperty(KAPTCHA_IMAGE_HEIGHT, "60");
// 验证码文本字符大小 默认为40
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_SIZE, "35");
// KAPTCHA_SESSION_KEY
properties.setProperty(KAPTCHA_SESSION_CONFIG_KEY, "kaptchaCodeMath");
// 验证码文本生成器
// 这个要自己定位
properties.setProperty(KAPTCHA_TEXTPRODUCER_IMPL, "com.zhao.config.KaptchaTextCreator");
// 验证码文本字符间距 默认为2
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_SPACE, "3");
// 验证码文本字符长度 默认为5
properties.setProperty(KAPTCHA_TEXTPRODUCER_CHAR_LENGTH, "6");
// 验证码文本字体样式 默认为new Font("Arial", 1, fontSize), new Font("Courier", 1, fontSize)
properties.setProperty(KAPTCHA_TEXTPRODUCER_FONT_NAMES, "Arial,Courier");
// 验证码噪点颜色 默认为Color.BLACK
properties.setProperty(KAPTCHA_NOISE_COLOR, "white");
// 干扰实现类
properties.setProperty(KAPTCHA_NOISE_IMPL, "com.google.code.kaptcha.impl.NoNoise");
// 图片样式 水纹com.google.code.kaptcha.impl.WaterRipple 鱼眼com.google.code.kaptcha.impl.FishEyeGimpy 阴影com.google.code.kaptcha.impl.ShadowGimpy
properties.setProperty(KAPTCHA_OBSCURIFICATOR_IMPL, "com.google.code.kaptcha.impl.ShadowGimpy");
Config config = new Config(properties);
defaultKaptcha.setConfig(config);
return defaultKaptcha;
}
}
package com.zhao.config;
import com.google.code.kaptcha.text.impl.DefaultTextCreator;
import java.util.Random;
/**
* 验证码文本生成器
*
* @author ruoyi
*/
public class KaptchaTextCreator extends DefaultTextCreator
{
private static final String[] CNUMBERS = "0,1,2,3,4,5,6,7,8,9,10".split(",");
@Override
public String getText()
{
Integer result = 0;
Random random = new Random();
int x = random.nextInt(10);
int y = random.nextInt(10);
StringBuilder suChinese = new StringBuilder();
int randomoperands = random.nextInt(3);
if (randomoperands == 0)
{
result = x * y;
suChinese.append(CNUMBERS[x]);
suChinese.append("*");
suChinese.append(CNUMBERS[y]);
}
else if (randomoperands == 1)
{
if ((x != 0) && y % x == 0)
{
result = y / x;
suChinese.append(CNUMBERS[y]);
suChinese.append("/");
suChinese.append(CNUMBERS[x]);
}
else
{
result = x + y;
suChinese.append(CNUMBERS[x]);
suChinese.append("+");
suChinese.append(CNUMBERS[y]);
}
}
else
{
if (x >= y)
{
result = x - y;
suChinese.append(CNUMBERS[x]);
suChinese.append("-");
suChinese.append(CNUMBERS[y]);
}
else
{
result = y - x;
suChinese.append(CNUMBERS[y]);
suChinese.append("-");
suChinese.append(CNUMBERS[x]);
}
}
suChinese.append("=?@" + result);
return suChinese.toString();
}
}
@Autowired
RedisUtil redisUtil;
@Override
public R login(LoginDTO loginDTO) {
// 取出redis中的值
Object o = redisUtil.get("captcha_codes:" + loginDTO.getUuid());
// 验证验证码是否正确
if (!loginDTO.getCode().toString().equals(o.toString())){
return R.Failed("验证码错误");
}
// 这下面就不用看了
User loginUser = new User();
loginUser.setUserName(loginDTO.getUserName())
.setPassword(loginDTO.getPassword());
try {
User user = this.baseMapper.selectOne(
new LambdaQueryWrapper<User>()
.eq(User::getUserName, loginUser.getUserName())
.eq(User::getPassword, MD5Util.md5(loginUser.getPassword())));
if (user!=null){
Map<String,Object> map = new HashMap<>(2);
map.put("userId",user.getUserId());
map.put("jurisdiction",user.getJurisdiction());
String token = Auth0JwtUtils.sign(map);
Map<String , String> map2 = new HashMap<>(1);
map2.put("token",token);
return R.Success(map2);
}
} catch (NoSuchAlgorithmException e) {
log.error(e.getMessage());
return R.Failed("账号密码错误");
}
return R.Failed("账号密码错误");
}