springSecurity 图片验证码

本贴最后更新于 2022 天前,其中的信息可能已经斗转星移

简介

验证码(CAPTCHA)的全称是 Completely Automated Public Turing test to tell Computers and
Humans Apart,翻译过来就是“全自动区分计算机和人类的图灵测试”。通俗地讲,验证码就是为了防
止恶意用户暴力重试而设置的。不管是用户注册、用户登录,还是论坛发帖,如果不加以限制,一旦
某些恶意用户利用计算机发起无限重试,就很容易使系统遭受破坏。

通过过滤器实现

自定义过滤器
在 Spring Security 中,实现验证码校验的方式有很多种,最简单的方式就是自定义一个专门处理验
证码逻辑的过滤器,将其添加到 Spring Security 过滤器链的合适位置。当匹配到登录请求时,立刻对验
证码进行校验,成功则放行,失败则提前结束整个验证请求。
图形验证码过滤器

  • 1、验证码图片准备
    毋庸置疑,要想实现图形验证码校验功能,首先应当有一个用于获取图形验证码的 API。绘制图
    形验证码的方法有很多,使用开源的验证码组件即可,例如 kaptcha
<dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>2.3.2</version> </dependency>

首先配置一个 kaptcha 实例

package club.xwzzy.springbootsecurity_imageverification.config; import com.google.code.kaptcha.Producer; import com.google.code.kaptcha.impl.DefaultKaptcha; import com.google.code.kaptcha.util.Config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; @Configuration public class CaptchaConfig { @Bean public Producer captcha() { // 配置图形验证码的基本参数 Properties properties = new Properties(); // 图片宽度 properties.setProperty("kaptcha.image.width", "150"); // 图片长度 properties.setProperty("kaptcha.image.height", "50"); // 字符集 properties.setProperty("kaptcha.textproducer.char.string", "0123456789"); // 字符长度 properties.setProperty("kaptcha.textproducer.char.length", "4"); Config config = new Config(properties); // 使用默认的图形验证码实现,当然也可以自定义实现 DefaultKaptcha defaultKaptcha = new DefaultKaptcha(); defaultKaptcha.setConfig(config); return defaultKaptcha; } }

接着创建一个 CaptchaController,用于获取图形验证码。

package club.xwzzy.springbootsecurity_imageverification.controller; import com.google.code.kaptcha.Producer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.IOException; @Controller public class CaptchaController { @Autowired private Producer captchaProducer; @GetMapping("/captcha.jpg") public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException { // 设置内容类型 response.setContentType("image/jpeg"); // 创建验证码文本 String capText = captchaProducer.createText(); // 将验证码文本设置到session request.getSession().setAttribute("captcha", capText); // 创建验证码图片 BufferedImage bi = captchaProducer.createImage(capText); // 获取响应输出流 ServletOutputStream out = response.getOutputStream(); // 将图片验证码数据写到响应输出流 ImageIO.write(bi, "jpg", out); // 推送并关闭响应输出流 try { out.flush(); } finally { out.close(); } } }

当用户访问/captcha.jpg 时,即可得到一张携带验证码的图片,验证码文本则被存放到 session 中用于后续的校验。

  • 2、自定义异常
package club.xwzzy.springbootsecurity_imageverification.exception; import org.springframework.security.core.AuthenticationException; public class VerificationCodeException extends AuthenticationException { public VerificationCodeException () { super("图形验证码校验失败"); } }
  • 3、自定义过滤器
package club.xwzzy.springbootsecurity_imageverification.filter; import club.xwzzy.springbootsecurity_imageverification.authentication.SecurityAuthenticationFailureHandler; import club.xwzzy.springbootsecurity_imageverification.exception.VerificationCodeException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.util.StringUtils; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class VerificationCodeFilter extends OncePerRequestFilter { private AuthenticationFailureHandler authenticationFailureHandler = new SecurityAuthenticationFailureHandler(); @Override protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException { // 非登录请求不校验验证码 if (!"/login".equals(httpServletRequest.getRequestURI())) { filterChain.doFilter(httpServletRequest, httpServletResponse); } else { try { verificationCode(httpServletRequest); filterChain.doFilter(httpServletRequest, httpServletResponse); } catch (VerificationCodeException e) { authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e); } } } public void verificationCode (HttpServletRequest httpServletRequest) throws VerificationCodeException { String requestCode = httpServletRequest.getParameter("captcha"); HttpSession session = httpServletRequest.getSession(); String savedCode = (String) session.getAttribute("captcha"); if (!StringUtils.isEmpty(savedCode)) { // 随手清除验证码,不管是失败还是成功,所以客户端应在登录失败时刷新验证码 session.removeAttribute("captcha"); } // 校验不通过抛出异常 if (StringUtils.isEmpty(requestCode) || StringUtils.isEmpty(savedCode) || !requestCode.equals(savedCode)) { throw new VerificationCodeException(); } } }
  • 4、添加过滤器
// 将过滤器添加在UsernamePasswordAuthenticationFilter之前 http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
  • 5、html
<!DOCTYPE HTML> <html> <head> <title>登录</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <div class="login"> <h2>Acced Form</h2> <div class="login-top"> <h1>LOGIN FORM</h1> <form action="/login" method="post"> <input type="text" name="username" placeholder="username" /> <input type="password" name="password" placeholder="password" /> <div style="display: flex;"> <!-- 新增图形验证码的输入框 --> <input type="text" name="captcha" placeholder="captcha" /> <!-- 图片指向图形验证码API --> <img src="/captcha.jpg" alt="captcha" height="50px" width="150px" style="margin-left: 20px;"> </div> <div class="forgot"> <a href="#">forgot Password</a> <input type="submit" value="Login" > </div> </form> </div> <div class="login-bottom"> <h3>New User &nbsp;<a href="#">Register</a>&nbsp Here</h3> </div> </div> <style> html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,dl,dt,dd,ol,nav ul,nav li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline;} article, aside, details, figcaption, figure,footer, header, hgroup, menu, nav, section {display: block;} ol,ul{list-style:none;margin:0;padding:0;} blockquote,q{quotes:none;} blockquote:before,blockquote:after,q:before,q:after{content:'';content:none;} table{border-collapse:collapse;border-spacing:0;} a{text-decoration:none;} nav.vertical ul li{ display:block;} nav.horizontal ul li{ display: inline-block;} img{max-width:100%;} body{ background: #3f3f3f; padding:100px 0px 30px 0px; font-family: 'Roboto', sans-serif; font-size: 100%; } .login { width: 32%; margin: 0 auto; } .login h2 { font-size: 30px; font-weight: 700; color: #fff; text-align: center; margin: 0px 0px 50px 0px; font-family: 'Droid Serif', serif; } .login-top { background: #E1E1E1; border-radius: 25px 25px 0px 0px; -webkit-border-radius: 25px 25px 0px 0px; -moz-border-radius: 25px 25px 0px 0px; -o-border-radius: 25px 25px 0px 0px; padding: 40px 60px; } .login-top h1 { text-align: center; font-size: 27px; font-weight: 500; color: #F45B4B; margin: 0px 0px 20px 0px; } .login-top input[type="text"] { outline: none; font-size: 15px; font-weight: 500; color: #818181; padding: 15px 20px; background: #CACACA; border: 1px solid #ccc; border-radius:25px; -webkit-border-radius: 25px; -moz-border-radius: 25px; -o-border-radius: 25px; margin: 0px 0px 12px 0px; width: 88%; -webkit-appearance: none; } .login-top input[type="password"]{ outline: none; font-size: 15px; font-weight: 500; color: #818181; padding: 15px 20px; background: #CACACA; border: 1px solid #ccc; border-radius:25px; -webkit-border-radius: 25px; -moz-border-radius: 25px; -o-border-radius: 25px; margin: 0px 0px 12px 0px; width: 88%; -webkit-appearance: none; } .forgot a{ font-size: 13px; font-weight: 500; color: #F45B4B; display: inline-block; border-right: 2px solid #F45B4B; padding: 0px 7px 0px 0px; } .forgot a:hover{ color: #818181; } .forgot input[type="submit"] { background: #F45B4B; color: #FFF; font-size: 17px; font-weight: 400; padding: 8px 7px; width: 20%; display: inline-block; cursor: pointer; border-radius: 6px; -webkit-border-radius: 19px; -moz-border-radius: 6px; -o-border-radius: 6px; margin: 0px 7px 0px 3px; outline: none; border: none; } .forgot input[type="submit"]:hover { background:#818181; transition: 0.5s all; -webkit-transition: 0.5s all; -moz-transition: 0.5s all; -o-transition: 0.5s all; } .forgot { text-align: right; } .login-bottom { background: #E15748; padding: 30px 65px; border-radius: 0px 0px 25px 25px; -webkit-border-radius: 0px 0px 25px 25px; -moz-border-radius: 0px 0px 25px 25px; -o-border-radius: 0px 0px 25px 25px; text-align: right; border-top: 2px solid #AD4337; } .login-bottom h3 { font-size: 14px; font-weight: 500; color: #fff; } .login-bottom h3 a { font-size: 25px; font-weight: 500; color: #fff; } .login-bottom h3 a:hover { color:#696969; transition: 0.5s all; -webkit-transition: 0.5s all; -moz-transition: 0.5s all; -o-transition: 0.5s all; } .copyright p { font-size: 15px; font-weight: 400; color: #fff; } .copyright p a{ font-size: 15px; font-weight: 400; color: #E15748; } .copyright p a:hover{ color: #fff; transition: 0.5s all; -webkit-transition: 0.5s all; -moz-transition: 0.5s all; -o-transition: 0.5s all; } @media(max-width:1440px){ .login { width: 35%; } } @media(max-width:1366px){ .login { width: 37%; } } @media(max-width:1280px){ .login { width: 40%; } } @media(max-width:1024px){ .login { width: 48%; } } @media(max-width:768px){ .login { width: 65%; } .login-top h1 { font-size: 25px; } .login-bottom h3 a { font-size: 22px; } body { padding: 100px 0px 0px 0px; } .login h2 { font-size: 28px; } } @media(max-width:640px){ .login-top h1 { font-size: 23px; } .forgot input[type="submit"] { font-size: 15px; width: 22%; } .login-top input[type="text"] { padding: 12px 20px; } .login-top input[type="password"] { padding: 12px 20px; } .login-bottom h3 a { font-size: 19px; } .login-bottom h3 { font-size: 13px; } body { padding: 110px 0px 0px 0px; } } @media(max-width:480px){ .login { width: 80%; } .login-top h1 { font-size: 21px; } .login-top input[type="text"] { width: 85%; } .login-top { padding: 30px 40px; } .login-top input[type="password"] { width: 85%; } .login h2 { font-size: 25px; } } @media(max-width:320px){ .login { width: 90%; } .login-top { padding: 20px 25px; } .login-top input[type="text"] { width: 81%; padding: 10px 20px; font-size: 13px; margin: 0px 0px 7px 0px; } .login-top input[type="password"] { width: 81%; padding: 10px 20px; font-size: 13px; margin: 0px 0px 7px 0px; } .forgot input[type="submit"] { font-size: 11px; width: 25%; padding: 6px 7px; } .forgot a { font-size: 11px; } .login-bottom { padding: 20px 25px; } .login-bottom h3 { font-size: 11px; } .login-bottom h3 a { font-size: 17px; } body { padding: 50px 0px 0px 0px; } .copyright p { font-size: 13px; } .copyright p a{ font-size: 13px; } .login h2 { font-size: 23px; margin:0px 0px 35px 0px; } } </style> </body> </html>

至此,使用过滤器的方式实现验证码结束,属于 Servlet 层面,简单、易理解。
代码地址

  • Java

    Java 是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由 Sun Microsystems 公司于 1995 年 5 月推出的。Java 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3201 引用 • 8216 回帖 • 4 关注
  • Spring

    Spring 是一个开源框架,是于 2003 年兴起的一个轻量级的 Java 开发框架,由 Rod Johnson 在其著作《Expert One-On-One J2EE Development and Design》中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件,同时为 JavaEE 应用程序开发提供集成的框架。

    947 引用 • 1460 回帖 • 1 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...

推荐标签 标签

  • Gitea

    Gitea 是一个开源社区驱动的轻量级代码托管解决方案,后端采用 Go 编写,采用 MIT 许可证。

    5 引用 • 16 回帖 • 1 关注
  • Hadoop

    Hadoop 是由 Apache 基金会所开发的一个分布式系统基础架构。用户可以在不了解分布式底层细节的情况下,开发分布式程序。充分利用集群的威力进行高速运算和存储。

    93 引用 • 122 回帖 • 619 关注
  • 安全

    安全永远都不是一个小问题。

    199 引用 • 818 回帖
  • Swagger

    Swagger 是一款非常流行的 API 开发工具,它遵循 OpenAPI Specification(这是一种通用的、和编程语言无关的 API 描述规范)。Swagger 贯穿整个 API 生命周期,如 API 的设计、编写文档、测试和部署。

    26 引用 • 35 回帖 • 2 关注
  • 链书

    链书(Chainbook)是 B3log 开源社区提供的区块链纸质书交易平台,通过 B3T 实现共享激励与价值链。可将你的闲置书籍上架到链书,我们共同构建这个全新的交易平台,让闲置书籍继续发挥它的价值。

    链书社

    链书目前已经下线,也许以后还有计划重制上线。

    14 引用 • 257 回帖
  • danl
    173 关注
  • Elasticsearch

    Elasticsearch 是一个基于 Lucene 的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于 RESTful 接口。Elasticsearch 是用 Java 开发的,并作为 Apache 许可条款下的开放源码发布,是当前流行的企业级搜索引擎。设计用于云计算中,能够达到实时搜索,稳定,可靠,快速,安装使用方便。

    117 引用 • 99 回帖 • 195 关注
  • ZooKeeper

    ZooKeeper 是一个分布式的,开放源码的分布式应用程序协调服务,是 Google 的 Chubby 一个开源的实现,是 Hadoop 和 HBase 的重要组件。它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、域名服务、分布式同步、组服务等。

    59 引用 • 29 回帖 • 9 关注
  • Flutter

    Flutter 是谷歌的移动 UI 框架,可以快速在 iOS 和 Android 上构建高质量的原生用户界面。 Flutter 可以与现有的代码一起工作,它正在被越来越多的开发者和组织使用,并且 Flutter 是完全免费、开源的。

    39 引用 • 92 回帖 • 7 关注
  • 周末

    星期六到星期天晚,实行五天工作制后,指每周的最后两天。再过几年可能就是三天了。

    14 引用 • 297 回帖 • 1 关注
  • 持续集成

    持续集成(Continuous Integration)是一种软件开发实践,即团队开发成员经常集成他们的工作,通过每个成员每天至少集成一次,也就意味着每天可能会发生多次集成。每次集成都通过自动化的构建(包括编译,发布,自动化测试)来验证,从而尽早地发现集成错误。

    15 引用 • 7 回帖 • 1 关注
  • SSL

    SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS 与 SSL 在传输层对网络连接进行加密。

    70 引用 • 193 回帖 • 414 关注
  • Bug

    Bug 本意是指臭虫、缺陷、损坏、犯贫、窃听器、小虫等。现在人们把在程序中一些缺陷或问题统称为 bug(漏洞)。

    76 引用 • 1742 回帖 • 2 关注
  • 链滴

    链滴是一个记录生活的地方。

    记录生活,连接点滴

    180 引用 • 3878 回帖 • 1 关注
  • 设计模式

    设计模式(Design pattern)代表了最佳的实践,通常被有经验的面向对象的软件开发人员所采用。设计模式是软件开发人员在软件开发过程中面临的一般问题的解决方案。这些解决方案是众多软件开发人员经过相当长的一段时间的试验和错误总结出来的。

    201 引用 • 120 回帖 • 2 关注
  • JRebel

    JRebel 是一款 Java 虚拟机插件,它使得 Java 程序员能在不进行重部署的情况下,即时看到代码的改变对一个应用程序带来的影响。

    26 引用 • 78 回帖 • 675 关注
  • 外包

    有空闲时间是接外包好呢还是学习好呢?

    26 引用 • 233 回帖
  • 七牛云

    七牛云是国内领先的企业级公有云服务商,致力于打造以数据为核心的场景化 PaaS 服务。围绕富媒体场景,七牛先后推出了对象存储,融合 CDN 加速,数据通用处理,内容反垃圾服务,以及直播云服务等。

    29 引用 • 230 回帖 • 122 关注
  • 运维

    互联网运维工作,以服务为中心,以稳定、安全、高效为三个基本点,确保公司的互联网业务能够 7×24 小时为用户提供高质量的服务。

    151 引用 • 257 回帖 • 1 关注
  • Follow
    4 引用 • 12 回帖 • 1 关注
  • 资讯

    资讯是用户因为及时地获得它并利用它而能够在相对短的时间内给自己带来价值的信息,资讯有时效性和地域性。

    56 引用 • 85 回帖
  • JavaScript

    JavaScript 一种动态类型、弱类型、基于原型的直译式脚本语言,内置支持类型。它的解释器被称为 JavaScript 引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在 HTML 网页上使用,用来给 HTML 网页增加动态功能。

    730 引用 • 1282 回帖 • 5 关注
  • Webswing

    Webswing 是一个能将任何 Swing 应用通过纯 HTML5 运行在浏览器中的 Web 服务器,详细介绍请看 将 Java Swing 应用变成 Web 应用

    1 引用 • 15 回帖 • 645 关注
  • Wide

    Wide 是一款基于 Web 的 Go 语言 IDE。通过浏览器就可以进行 Go 开发,并有代码自动完成、查看表达式、编译反馈、Lint、实时结果输出等功能。

    欢迎访问我们运维的实例: https://wide.b3log.org

    30 引用 • 218 回帖 • 644 关注
  • Solo

    Solo 是一款小而美的开源博客系统,专为程序员设计。Solo 有着非常活跃的社区,可将文章作为帖子推送到社区,来自社区的回帖将作为博客评论进行联动(具体细节请浏览 B3log 构思 - 分布式社区网络)。

    这是一种全新的网络社区体验,让热爱记录和分享的你不再感到孤单!

    1443 引用 • 10082 回帖 • 497 关注
  • CodeMirror
    2 引用 • 17 回帖 • 167 关注
  • 音乐

    你听到信仰的声音了么?

    62 引用 • 512 回帖