SpringBoot+Vue项目中实现登录验证码校验
在各大项目中,为保证数据的安全性,通常在登录页面加入验证码校验,以防止爬虫带来的数据泄露危机。本文将介绍在前后端分离的项目中,怎样实现图形验证码校验。
实现思路
第一步:在后端创建一个生成随机验证码的工具类和接收请求验证码的接口。工具类的主要作用生成随机验证码和对应的图片。接口的作用是将生成的随机验证码保存到session,同时,将图片进行base64编码,然后返回给前端。
第二步:在登录页面创建的同时获取验证码,并将后端传回来得key和编码后的字符串拼接,绑定img标签的src属性。此外,当用户点击验证码的img标签时,重新获取验证码,后端session更新验证码。
第三步:后端登录接口接收登录请求时,将用户提交的验证码和session中的验证码进行比对,不相同则返回相应信息给前端进行提示,相同则进行账号密码的匹配。
测试案例
- 创建验证码生成的工具类
package com.check.utils;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class CreateImageCode {
// 图片的宽度。
private int width = 160;
// 图片的高度。
private int height = 40;
// 验证码字符个数
private int codeCount = 4;
// 验证码干扰线数
private int lineCount = 20;
// 验证码
private String code = null;
// 验证码图片Buffer
private BufferedImage buffImg = null;
Random random = new Random();
public CreateImageCode() {
creatImage();
}
public CreateImageCode(int width, int height) {
this.width = width;
this.height = height;
creatImage();
}
public CreateImageCode(int width, int height, int codeCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
creatImage();
}
public CreateImageCode(int width, int height, int codeCount, int lineCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
creatImage();
}
// 生成图片
private void creatImage() {
int fontWidth = width / codeCount;// 字体的宽度
int fontHeight = height - 5;// 字体的高度
int codeY = height - 8;
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = buffImg.getGraphics();
//Graphics2D g = buffImg.createGraphics();
// 设置背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设置字体
//Font font1 = getFont(fontHeight);
Font font = new Font("Fixedsys", Font.BOLD, fontHeight)