一文轻松学会:SpringBoot图形验证码的生成

在很多情况下,我们需要生成图形验证码来提高系统的安全程度,比如获取手机验证码之前要输入图形验证码,比如答题或者抽奖之前要输入图形验证码,这样子提高了用户直接调用接口来刷的难度,为什么说只是提高了难度呢,因为如果想要破解的话还是可以破解的,用智能识别,跟库对比什么的就可以破解了,只不过破解成本高!

再比如12306的图形验证码是叫用户选择图片类型的,这种难度就更加高了,若是破解的付出不能大于收益,正常来说用户都不会去破解啦。

这里实现的是最简单的图形验证码,后台自动生成四位随机数,然后合成图片流返回给页面,要注意的是这个验证码一定要后台生成,不可以是前端传过去,不然就没有意义了,可以放session,也可以放入redis.

下面是代码例子,我这个是基于SpringBoot的,不过其他框架也是一样,主要是返回图片流即可,这里还要注意加上一个配置类。

页面的使用方式可以直接是:将这个请求路径写在img标签的src中,每次刷新就改变src的值,后面加一个时间戳。

<code>http://localhost:8080/get/<code>

代码如下:

<code>@RestController
public class MyController {
@RequestMapping(value = "/get",produces = MediaType.IMAGE_JPEG_VALUE)
@ResponseBody
public BufferedImage getImage() throws IOException {
SecureRandom random = new SecureRandom();
//图形验证码的宽度
int width=75;

//图形验证码的高度
int height = 30;
//图形验证码的颜色
Color backColor = new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
//图形验证码的字体颜色,跟背景颜色反色
Color fontColor = new Color(255-backColor.getRed(),255-backColor.getGreen(),255-backColor.getBlue());
//生成BufferedImage对象
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//得到画布
Graphics2D g = bi.createGraphics();
//获取字体:Sans Serif字体比较难以阅读,增加辨识难度
Font font = new Font(Font.SANS_SERIF, Font.BOLD, 20);
//设置字体
g.setFont(font);
//设置画笔颜色
g.setColor(backColor);
//画背景
g.fillRect(0, 0, width, height);
//设置画笔颜色
g.setColor(fontColor);
//获取要画的验证码
String seq = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ";
StringBuffer sb = new StringBuffer();
int j = 0;
for(int i=0;i<4;i++) {
j=random.nextInt(seq.length());
sb.append(seq.substring(j, j+1));
}
String code = sb.toString();
//画字符:画布宽度75,高度30,文字大小20,四个文字长度就是
//计算文字长度
FontMetrics fm = g.getFontMetrics(font);
int textWidth = fm.stringWidth(code);
int w = (width-textWidth)/2;
g.drawString(code, w, 22);
//画噪点:40个
for(int i=0;i<40;i++) {
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));

g.fillRect(random.nextInt(width), random.nextInt(height), 1, 1);
}
//返回图片流
return bi;
}
}
@Configuration
class My extends WebMvcConfigurationSupport{
@Override
protected void extendMessageConverters(List<httpmessageconverter>> converters) {
converters.add(new BufferedImageHttpMessageConverter());
}
}/<httpmessageconverter>/<code>

注意事项:

有时候如果我们直接使用继承WebMvcConfigurationSupport会影响资源文件的加载。此时我们可以改为实现:WebMvcConfiger

<code>public class My implements WebMvcConfiger{
...
  @Override
public void extendMessageConverters(List<httpmessageconverter>> converters) {
converters.add(new BufferedImageHttpMessageConverter());
}
...
}/<httpmessageconverter>/<code>


启动测试:

这里就直接浏览器访问如下链接即可

<code>http://localhost:8080/get/<code>


一文轻松学会:SpringBoot图形验证码的生成


分享到:


相關文章: