本文介绍了SpringBoot结合SpringSecurity实现图形验证码功能,分享给大家,具体如下:
生成图形验证码
-
<李>根据随机数生成图片李>
<李>将随机数存到会话中李>
<李>将生成的图片写到接口的响应中李>
生成图形验证码的过程比较简单,和SpringSecurity也没有什么关系,所以就直接贴出代码了
<强>根据随机数生成图片强>
/* * *生成图形验证码 * @param请求 * @return */私人ImageCode生成(ServletWebRequest请求){ int宽度=64; int高度=32; BufferedImage图像=new BufferedImage(宽度、高度,BufferedImage.TYPE_INT_RGB); 图g=image.getGraphics (); 随机随机=new随机(); g。改变颜色(getRandColor (200、250)); g。fillRect(0, 0,宽度、高度); g。setFont(新字体(“Times new Roman字体。斜体,20)); g。改变颜色(getRandColor (160、200)); for (int i=0;我& lt;155;我+ +){ int x=random.nextInt(宽度); int y=random.nextInt(高度); int xl=random.nextInt (12); int yl=random.nextInt (12); g。画直线(x + xl x, y, y +黄); } 字符串将sRand=" "; for (int i=0;我& lt;4;我+ +){ 字符串兰德=String.valueOf (random.nextInt (10)); 将sRand +=兰德; g。改变颜色(新颜色(20 + random.nextInt (110), 20 + random.nextInt (110), 20 + random.nextInt (110))); g。拉带(兰德,13 *我+ 6,16); } g.dispose (); 返回新ImageCode(图像,将sRand 60); }/* * *生成随机背景条纹 * * @param fc * @param公元前 * @return */私人颜色getRandColor(公元前int fc, int) { 随机随机=new随机(); 如果(fc祝辞255){ fc=255; } 如果(公元前比;255){ 公元前=255; } int r=fc +随机的。nextInt (bc - fc); int g=fc +随机的。nextInt (bc - fc); int b=fc +随机的。nextInt (bc - fc); 返回新颜色(r, g, b); } >之前<强>将随机数存到会话中,,将生成的图片写到接口的响应中强>
@RestController 公开课ValidateCodeController { 公共静态最终字符串SESSION_KEY=癝ESSION_KEY_IMAGE_CODE”; 私人SessionStrategy SessionStrategy=new HttpSessionSessionStrategy (); @GetMapping(“/代码/形象”) 公共空createCode (HttpServletRequest请求,HttpServletResponse响应)抛出IOException { ImageCode ImageCode=生成(新ServletWebRequest(请求)); sessionStrategy。setAttribute(新ServletWebRequest(请求),SESSION_KEY imageCode); ImageIO.write (imageCode.getImage (), JPEG, response.getOutputStream ()); } } >之前<强>在认证流程中加入图形验证码强>
在SpringSecurity认证流程详解中,我们有讲到,SpringSecurity是通过过滤器链来进行校验的,我们想要验证图形验证码,所以可以在认证流程之前,也就是<代码> UsernamePasswordAuthenticationFilter 代码>之前进行校验。
自定义图形验证码的过滤器
@ component 公开课ValidateCodeFilter扩展> @Override 保护无效配置(HttpSecurity http){抛出异常 ValidateCodeFilter ValidateCodeFilter=new ValidateCodeFilter (); validateCodeFilter.setAuthenticationFailureHandler (myAuthenticationFailureHandler);//将我们自定义的过滤器,配置到UsernamePasswordAuthenticationFilter之前 http。addFilterBefore (validateCodeFilter UsernamePasswordAuthenticationFilter.class) .formLogin()//定义当需要用户登录时候,转到的登录页面。//后面的配置省略 } >之前<强>代码下载强>
spring security
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
SpringBoot结合SpringSecurity实现图形验证码功能