热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

SpringSecurity实现图形验证码功能的实例代码

SpringSecurity的前身是AcegiSecurity,是Spring项目组中用来提供安全认证服务的框架。这篇文章主要介绍了SpringSecurity实现图形验证码功能,需要的朋友可以参考下

Spring Security

Spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。它提供了一组可以在Spring应用上下文中配置的Bean,充分利用了Spring IoC,DI(控制反转Inversion of Control ,DI:Dependency Injection 依赖注入)和AOP(面向切面编程)功能,为应用系统提供声明式的安全访问控制功能,减少了为企业系统安全控制编写大量重复代码的工作。

Spring Security

下载:https://github.com/whyalwaysmea/Spring-Security

本文重点给大家介绍SpringSecurity实现图形验证码功能,具体内容如下:

1.开发生成图形验证码接口

-> 封装ImageCode对象,来存放图片验证码的内容、图片以及有效时间

public class ImageCode {
 private BufferedImage image;// 图片
 private String code;// 验证码
 private LocalDateTime expireTime;// 有效时间
 public ImageCode(BufferedImage image, String code, int expireIn) {
 this.image = image;
 this.code = code;
 // 出入一个秒数,自动转为时间,如过期时间为60s,这里的expireIn就是60,转换为当前时间上加上这个秒数
 this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
 }
 public ImageCode(BufferedImage image, String code, LocalDateTime expireTime) {
 this.image = image;
 this.code = code;
 this.expireTime = expireTime;
 }
 public BufferedImage getImage() {
 return image;
 }
 public void setImage(BufferedImage image) {
 this.image = image;
 }
 public String getCode() {
 return code;
 }
 public void setCode(String code) {
 this.code = code;
 }
 public LocalDateTime getExpireTime() {
 return expireTime;
 }
 public void setExpireTime(LocalDateTime expireTime) {
 this.expireTime = expireTime;
 }
}

-> 写一个Controller用于生成图片和校验验证码

public class ValidateCodeController {
 private 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 = createImageCode(request);
 // 将随机数存到session中
 sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
 // 将生成的图片写到接口的响应中
 ImageIO.write(imageCode.getImage(), "JPEG", response.getOutputStream());
 }

 private ImageCode createImageCode(HttpServletRequest request) {
 // 图片的宽高(像素)
 int width = 67;
 int height = 23;
 // 生成图片对象
 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, xl, 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();
 // 60秒有效
 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);
 }
}

第一步:根据随机数生成图片

ImageCode imageCode = createImageCode(request);

第二步:将随机数存到session中

sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);

第三步:将生成的图片写到接口的响应中

ImageIO.write(imageCode.getImage(), “JPEG”, response.getOutputStream());

-> 在静态页面中加入图片验证码的标签


 图形验证码:
 
 
 
 

-> 将接口请求地址配进认证

@Override
protected void configure(HttpSecurity http) throws Exception {
 http.formLogin()
 .loginPage("/authencation/require")
 .loginProcessingUrl("/authentication/form")
 .successHandler(imoocAuthenticationSuccessHandler)
 .failureHandler(imoocAuthenticationFailureHandler)
 .and()
 .authorizeRequests()
 .antMatchers("/authencation/require", 
 securityPropertis.getBrowserPropertis().getLoginPage(),
 "/code/image").permitAll() // 加入"/code/image"地址
 .anyRequest()
 .authenticated()
 .and()
 .csrf().disable();
}

->启动服务器访问静态表单

如图所示:

图片验证码

2.在认证流程中加入图形验证码校验

-> 写一个filter进行拦截
public class ValidateCodeFilter extends OncePerRequestFilter{
 private AuthenticationFailureHandler authenticationFailureHandler;
 private SessionStrategy sessiOnStrategy= new HttpSessionSessionStrategy();
 @Override
 protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
 throws ServletException, IOException {
 //如果访问的是/authentication/form并且为post请求
 if(StringUtils.equals("/authentication/form", request.getRequestURI())
 && StringUtils.equals(request.getMethod(), "post")) {
 try {
 // 验证图片验证码是否填写正确
 validate(new ServletWebRequest(request));
 } catch (ValidateCodeException e) {
 // 抛出异常,并返回,不再访问资源
 authenticationFailureHandler.onAuthenticationFailure(request, response, e);
 return;
 }
 }
 // 通过,执行后面的filter
 filterChain.doFilter(request, response);
 }
 // 校验验证码的逻辑
 private void validate(ServletWebRequest request) throws ServletRequestBindingException {
 ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(request, ValidateCodeController.SESSION_KEY);
 String codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(), "imageCode");
 if(StringUtils.isBlank(codeInRequest)) {
 throw new ValidateCodeException("验证码的值不能为空");
 }
 if(codeInSession == null){
 throw new ValidateCodeException("验证码不存在");
 }
 if(codeInSession.isExpried()) {
 sessionStrategy.removeAttribute(request, ValidateCodeController.SESSION_KEY);
 throw new ValidateCodeException("验证码已过期");
 }
 if(!StringUtils.equals(codeInSession.getCode(), codeInRequest)) {
 throw new ValidateCodeException("验证码不匹配");
 }
 sessionStrategy.removeAttribute(request, ValidateCodeController.SESSION_KEY);
 }
 public AuthenticationFailureHandler getAuthenticationFailureHandler() {
 return authenticationFailureHandler;
 }
 public void setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) {
 this.authenticatiOnFailureHandler= authenticationFailureHandler;
 }
 public SessionStrategy getSessionStrategy() {
 return sessionStrategy;
 }
 public void setSessionStrategy(SessionStrategy sessionStrategy) {
 this.sessiOnStrategy= sessionStrategy;
 }
}

-> 配置再configure中,生效

@Override
protected void configure(HttpSecurity http) throws Exception {
 // 声明filter
 ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
 // 配置验证失败执行的handler
 validateCodeFilter.setAuthenticationFailureHandler(imoocAuthenticationFailureHandler);
 // 添加filter到认证流程
 http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
 .formLogin()
 .loginPage("/authencation/require")
 .loginProcessingUrl("/authentication/form")
 .successHandler(imoocAuthenticationSuccessHandler)
 .failureHandler(imoocAuthenticationFailureHandler)
 .and()
 .authorizeRequests()
 .antMatchers("/authencation/require", 
 securityPropertis.getBrowserPropertis().getLoginPage(),
 "/code/image").permitAll()
 .anyRequest()
 .authenticated()
 .and()
 .csrf().disable();
}

至此,图片验证码验证流程已经全部完成。

启动服务,进行测试即可。

总结

到此这篇关于SpringSecurity实现图形验证码功能的实例代码的文章就介绍到这了,更多相关SpringSecurity图形验证码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


推荐阅读
  • 在现代网络环境中,两台计算机之间的文件传输需求日益增长。传统的FTP和SSH方式虽然有效,但其配置复杂、步骤繁琐,难以满足快速且安全的传输需求。本文将介绍一种基于Go语言开发的新一代文件传输工具——Croc,它不仅简化了操作流程,还提供了强大的加密和跨平台支持。 ... [详细]
  • 网络运维工程师负责确保企业IT基础设施的稳定运行,保障业务连续性和数据安全。他们需要具备多种技能,包括搭建和维护网络环境、监控系统性能、处理突发事件等。本文将探讨网络运维工程师的职业前景及其平均薪酬水平。 ... [详细]
  • 从零开始构建完整手机站:Vue CLI 3 实战指南(第一部分)
    本系列教程将引导您使用 Vue CLI 3 构建一个功能齐全的移动应用。我们将深入探讨项目中涉及的每一个知识点,并确保这些内容与实际工作中的需求紧密结合。 ... [详细]
  • 科研单位信息系统中的DevOps实践与优化
    本文探讨了某科研单位通过引入云原生平台实现DevOps开发和运维一体化,显著提升了项目交付效率和产品质量。详细介绍了如何在实际项目中应用DevOps理念,解决了传统开发模式下的诸多痛点。 ... [详细]
  • 本文详细介绍了IBM DB2数据库在大型应用系统中的应用,强调其卓越的可扩展性和多环境支持能力。文章深入分析了DB2在数据利用性、完整性、安全性和恢复性方面的优势,并提供了优化建议以提升其在不同规模应用程序中的表现。 ... [详细]
  • 优化联通光猫DNS服务器设置
    本文详细介绍了如何为联通光猫配置DNS服务器地址,以提高网络解析效率和访问体验。通过智能线路解析功能,域名解析可以根据访问者的IP来源和类型进行差异化处理,从而实现更优的网络性能。 ... [详细]
  • 深入理解 SQL 视图、存储过程与事务
    本文详细介绍了SQL中的视图、存储过程和事务的概念及应用。视图为用户提供了一种灵活的数据查询方式,存储过程则封装了复杂的SQL逻辑,而事务确保了数据库操作的完整性和一致性。 ... [详细]
  • 数据库内核开发入门 | 搭建研发环境的初步指南
    本课程将带你从零开始,逐步掌握数据库内核开发的基础知识和实践技能,重点介绍如何搭建OceanBase的开发环境。 ... [详细]
  • 本文详细介绍了Java编程语言中的核心概念和常见面试问题,包括集合类、数据结构、线程处理、Java虚拟机(JVM)、HTTP协议以及Git操作等方面的内容。通过深入分析每个主题,帮助读者更好地理解Java的关键特性和最佳实践。 ... [详细]
  • 如何配置Unturned服务器及其消息设置
    本文详细介绍了Unturned服务器的配置方法和消息设置技巧,帮助用户了解并优化服务器管理。同时,提供了关于云服务资源操作记录、远程登录设置以及文件传输的相关补充信息。 ... [详细]
  • 网络攻防实战:从HTTP到HTTPS的演变
    本文通过一系列日记记录了从发现漏洞到逐步加强安全措施的过程,探讨了如何应对网络攻击并最终实现全面的安全防护。 ... [详细]
  • 本文详细介绍了如何在 Spring Boot 应用中通过 @PropertySource 注解读取非默认配置文件,包括配置文件的创建、映射类的设计以及确保 Spring 容器能够正确加载这些配置的方法。 ... [详细]
  • 本文深入探讨了SQL数据库中常见的面试问题,包括如何获取自增字段的当前值、防止SQL注入的方法、游标的作用与使用、索引的形式及其优缺点,以及事务和存储过程的概念。通过详细的解答和示例,帮助读者更好地理解和应对这些技术问题。 ... [详细]
  • 本章详细介绍SP框架中的数据操作方法,包括数据查找、记录查询、新增、删除、更新、计数及字段增减等核心功能。通过具体示例和详细解析,帮助开发者更好地理解和使用这些方法。 ... [详细]
  • 本文介绍了如何在具备多个IP地址的FTP服务器环境中,通过动态地址端口复用和地址转换技术优化网络配置。重点讨论了2Mb/s DDN专线连接、Cisco 2611路由器及内部网络地址规划。 ... [详细]
author-avatar
x-诗儿_683
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有