SpringBoot结合SpringSecurity实现图形验证码功能
作者:whyalwaysmea 发布时间:2023-02-25 16:04:52
标签:SpringBoot,SpringSecurity,验证码
本文介绍了SpringBoot结合SpringSecurity实现图形验证码功能,分享给大家,具体如下:
生成图形验证码
根据随机数生成图片
将随机数存到Session中
将生成的图片写到接口的响应中
生成图形验证码的过程比较简单,和SpringSecurity也没有什么关系。所以就直接贴出代码了
根据随机数生成图片
/**
* 生成图形验证码
* @param request
* @return
*/
private ImageCode generate(ServletWebRequest request) {
int width = 64;
int height = 32;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.ITALIC, 20));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
String sRand = "";
for (int i = 0; i < 4; i++) {
String rand = String.valueOf(random.nextInt(10));
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
g.dispose();
return new ImageCode(image, sRand, 60);
}
/**
* 生成随机背景条纹
*
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
将随机数存到Session中 && 将生成的图片写到接口的响应中
@RestController
public class ValidateCodeController {
public static final String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
@GetMapping("/code/image")
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
ImageCode imageCode = generate(new ServletWebRequest(request));
sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
}
}
在认证流程中加入图形验证码
在SpringSecurity认证流程详解中,我们有讲到,SpringSecurity是通过过滤器链来进行校验的,我们想要验证图形验证码,所以可以在认证流程之前,也就是UsernamePasswordAuthenticationFilter
之前进行校验。
自定义图形验证码的过滤器
@Component
public class ValidateCodeFilter extends OncePerRequestFilter {
private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();
private AuthenticationFailureHandler authenticationFailureHandler;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
if(StringUtils.equals("/user/login", httpServletRequest.getRequestURI())
&& StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), "post")) {
try {
// 1. 进行验证码的校验
validate(new ServletWebRequest(httpServletRequest));
} catch (ValidateCodeException e) {
// 2. 如果校验不通过,调用SpringSecurity的校验失败处理器
authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
return ;
}
}
// 3. 校验通过,就放行
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
}
这里验证码校验的过程比较简单,主要就是判断传过来的参数和Session中保存的是否一致,以及Session中的验证码是否过期了。
有了自己的验证码过滤器之后,我们还需要将它配置在UsernamePasswordAuthenticationFilter之前:
@Override
protected void configure(HttpSecurity http) throws Exception {
ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
validateCodeFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);
// 将我们自定义的过滤器,配置到UsernamePasswordAuthenticationFilter之前
http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
.formLogin() // 定义当需要用户登录时候,转到的登录页面。
// 后面的配置省略
}
代码下载
Spring-Security
来源:https://blog.csdn.net/u013435893/article/details/79617872


猜你喜欢
- Java8实现菜单树形数据当我们打开京东商城时,左侧的菜单依次分为 * 展示,这是如何实现的呢?本篇暂不讲述前端,只讲述如何使用java8 的
- 文件的读写是很多应用程序具有的功能,甚至某些应用程序就是围绕着某一种格式文件的处 理而开发的,所以文件读写是应用程序开发的一个基本功能。Qt
- 目录什么是Insets?Insets相关类InsetsStateInsetsStateControllerInsetsSourceInset
- 首先我们先看一下要模拟的界面 我们主要实现的就是ListView解析json文件中的数据,UI布局很简单不做赘述。 这里我们需要一个服务器来
- 编辑 项目目录/.idea/workspace.xml添加标签后,保存。重启idea即可。<component name="
- 前言 CompoundButton在XML文件中主要使用下面两个属性。checked:指定按钮的勾选状态,true表示勾选,fal
- 本文实例讲述了Java Web项目部署在Tomcat运行出错与解决方法。分享给大家供大家参考,具体如下:1、在部署Java Web项目的过程
- spring boot metrics是什么?针对应用监控指标暴露,spring boot有一套完整的解决方案,并且内置了好很多的指标收集器
- 针对实例化过程中会做什么的分析,其中主要的是怎么推断出构造方法,怎么进行匹配【1】前言实例化这一步便是在doCreateBean方法的 in
- 如果您通过以下的代码来获取定义的颜色值context.getResources().getColor(R.color.some_color_
- kotlin是一门基于jvm的编程语言,最近进行了关于kotlin和 anko的研究。并且结合现在的APP设计模式,设想了初步的开发方式。并
- 1.底层网络接口采用apache的httpclient连接池框架; 2.图片缓存采用基于LRU的算法; 3.网络接口采用监听者模式; 4.包
- 对于服务器端开发人员而言,调用第三方接口获取数据,将其“代理”转化并返给客户端几乎是家常便
- 1.创建项目时选择redis依赖2.修改配置文件,使用SpringBoot就避免了之前很多的xml文件2.1学过redis的同学都知道这个东
- 问题最近 Cordova 项目里有一个需求,这里需要从 assets 目录中读取文件,加载配置信息,并且代码中要用到。因为看到 gradle
- 前言当我们在手机上使用360安全卫士时,手机屏幕上时刻都会出现一个小浮动窗口,点击该浮动窗口可跳转到安全卫士的操作界面,而且该浮动窗口不受其
- @Transactional是我们在用Spring时候几乎逃不掉的一个注解,该注解主要用来声明事务。它的实现原理是通过Spring AOP在
- 问题描述今天在给SpringBoot项目配置 * 的时候发现怎么都进不到 * 的方法里面,在搜索引擎上看了无数篇关于配置 * 的文章都没有找
- 今天安装了jdk1.8、tomcat8、和maven3.5.2,弄好后在myeclipse新建了一个maven项目,项目默认是jdk1.5,
- 本文实例为大家分享了无限级联下拉列表框的的实现方法,具体内容如下可能有一个树型结构的表,它可能有ID,Name,ParentID,Level