这篇文章主要介绍了Spring Security实现验证码登录功能,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
在spring security实现登录注销功能的基础上进行开发。
1,添加生成验证码的控制器。
(1),生成验证码
/* * *引入安全配置属性类 */@ autowired 私人SecurityProperties SecurityProperties; @Override 公共ImageCode createCode (HttpServletRequest请求){//如果请求中有宽度参数,则用请求中的,否则用配置属性中的 int宽度=ServletRequestUtils.getIntParameter(请求,“宽度”,securityProperties.getWidth ());//高度(宽度) int高度=ServletRequestUtils.getIntParameter(请求,“高度”,securityProperties.getHeight ());//图片验证码字符个数 int长度=securityProperties.getLength ();//过期时间 int expireIn=securityProperties.getExpireIn (); 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;长度;我+ +){ 字符串兰德=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 expireIn); }/* * *生成随机背景条纹 */私人颜色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); }
(2),验证码控制器
公共静态最终字符串SESSION_KEY=癝ESSION_KEY_IMAGE_CODE”; @ autowired 私人ValidateCodeGenerator imageCodeGenerator;/* * *会议对象 */私人SessionStrategy SessionStrategy=new HttpSessionSessionStrategy (); @GetMapping(“/代码/形象”) 公共空createCode (HttpServletRequest请求,HttpServletResponse响应)抛出IOException { ImageCode ImageCode=imageCodeGenerator.createCode(请求);//将随机数放到会话中 sessionStrategy。setAttribute(新ServletWebRequest(请求),SESSION_KEY imageCode); request.getSession () .setAttribute (SESSION_KEY imageCode);//写给响应响应 响应。setHeader (“cache - control”,“没有商店,no - cache”); response.setContentType(“图像/jpeg”); ImageIO.write (imageCode.getImage (), JPEG, response.getOutputStream ()); }
(3),其它辅助类
@ data 公开课ImageCode {/* * *图片 */私人BufferedImage形象;/* * *随机数 */私人字符串代码;/* * *过期时间 */私人LocalDateTime expireTime; 公共ImageCode (BufferedImage形象,字符串的代码,LocalDateTime expireTime) { 这一点。形象=图像; 这一点。代码=代码; 这一点。expireTime=expireTime; } 公共ImageCode (BufferedImage形象,字符串的代码,int expireIn) { 这一点。形象=图像; 这一点。代码=代码;//当前时间加上设置过期的时间 这一点。expireTime=LocalDateTime.now () .plusSeconds (expireIn); } 公共布尔isExpried () {//如果过期时间在当前日期之前,则验证码过期 返回LocalDateTime.now () .isAfter (expireTime); } }
@ConfigurationProperties(前缀=皊so.security.code.image”) @ component @ data 公开课SecurityProperties {/* * *验证码宽度 */私人int宽度=67;/* * *高度 */私人int高度=23;/* * *长度(几个数字) */私人int长度=4;/* * *过期时间 */私人int expireIn=60;/* * *需要图形验证码的url */私人字符串url; }Spring Security实现验证码登录功能