springSecurity 图片验证码

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

简介

验证码(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 技术具有卓越的通用性、高效性、平台移植性和安全性。

    3206 引用 • 8217 回帖
  • Spring

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

    950 引用 • 1460 回帖 • 2 关注

相关帖子

欢迎来到这里!

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

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

推荐标签 标签

  • 前端

    前端技术一般分为前端设计和前端开发,前端设计可以理解为网站的视觉设计,前端开发则是网站的前台代码实现,包括 HTML、CSS 以及 JavaScript 等。

    248 引用 • 1342 回帖
  • Thymeleaf

    Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。类似 Velocity、 FreeMarker 等,它也可以轻易的与 Spring 等 Web 框架进行集成作为 Web 应用的模板引擎。与其它模板引擎相比,Thymeleaf 最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个 Web 应用。

    11 引用 • 19 回帖 • 413 关注
  • 倾城之链
    23 引用 • 66 回帖 • 189 关注
  • BND

    BND(Baidu Netdisk Downloader)是一款图形界面的百度网盘不限速下载器,支持 Windows、Linux 和 Mac,详细介绍请看这里

    107 引用 • 1281 回帖 • 36 关注
  • Webswing

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

    1 引用 • 15 回帖 • 669 关注
  • GraphQL

    GraphQL 是一个用于 API 的查询语言,是一个使用基于类型系统来执行查询的服务端运行时(类型系统由你的数据定义)。GraphQL 并没有和任何特定数据库或者存储引擎绑定,而是依靠你现有的代码和数据支撑。

    4 引用 • 3 回帖 • 11 关注
  • CAP

    CAP 指的是在一个分布式系统中, Consistency(一致性)、 Availability(可用性)、Partition tolerance(分区容错性),三者不可兼得。

    12 引用 • 5 回帖 • 660 关注
  • webpack

    webpack 是一个用于前端开发的模块加载器和打包工具,它能把各种资源,例如 JS、CSS(less/sass)、图片等都作为模块来使用和处理。

    43 引用 • 130 回帖 • 259 关注
  • Spark

    Spark 是 UC Berkeley AMP lab 所开源的类 Hadoop MapReduce 的通用并行框架。Spark 拥有 Hadoop MapReduce 所具有的优点;但不同于 MapReduce 的是 Job 中间输出结果可以保存在内存中,从而不再需要读写 HDFS,因此 Spark 能更好地适用于数据挖掘与机器学习等需要迭代的 MapReduce 的算法。

    74 引用 • 46 回帖 • 563 关注
  • Latke

    Latke 是一款以 JSON 为主的 Java Web 框架。

    71 引用 • 535 回帖 • 847 关注
  • Vue.js

    Vue.js(读音 /vju ː/,类似于 view)是一个构建数据驱动的 Web 界面库。Vue.js 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。

    269 引用 • 666 回帖 • 1 关注
  • Solidity

    Solidity 是一种智能合约高级语言,运行在 [以太坊] 虚拟机(EVM)之上。它的语法接近于 JavaScript,是一种面向对象的语言。

    3 引用 • 18 回帖 • 458 关注
  • Log4j

    Log4j 是 Apache 开源的一款使用广泛的 Java 日志组件。

    20 引用 • 18 回帖 • 60 关注
  • 链滴

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

    记录生活,连接点滴

    203 引用 • 4025 回帖
  • Angular

    AngularAngularJS 的新版本。

    26 引用 • 66 回帖 • 578 关注
  • Unity

    Unity 是由 Unity Technologies 开发的一个让开发者可以轻松创建诸如 2D、3D 多平台的综合型游戏开发工具,是一个全面整合的专业游戏引擎。

    27 引用 • 7 回帖 • 92 关注
  • Shell

    Shell 脚本与 Windows/Dos 下的批处理相似,也就是用各类命令预先放入到一个文件中,方便一次性执行的一个程序文件,主要是方便管理员进行设置或者管理用的。但是它比 Windows 下的批处理更强大,比用其他编程程序编辑的程序效率更高,因为它使用了 Linux/Unix 下的命令。

    126 引用 • 83 回帖 • 1 关注
  • 单点登录

    单点登录(Single Sign On)是目前比较流行的企业业务整合的解决方案之一。SSO 的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。

    9 引用 • 25 回帖 • 8 关注
  • OkHttp

    OkHttp 是一款 HTTP & HTTP/2 客户端库,专为 Android 和 Java 应用打造。

    16 引用 • 6 回帖 • 98 关注
  • DevOps

    DevOps(Development 和 Operations 的组合词)是一组过程、方法与系统的统称,用于促进开发(应用程序/软件工程)、技术运营和质量保障(QA)部门之间的沟通、协作与整合。

    59 引用 • 25 回帖 • 5 关注
  • Elasticsearch

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

    117 引用 • 99 回帖 • 190 关注
  • Markdown

    Markdown 是一种轻量级标记语言,用户可使用纯文本编辑器来排版文档,最终通过 Markdown 引擎将文档转换为所需格式(比如 HTML、PDF 等)。

    173 引用 • 1559 回帖
  • Wide

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

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

    30 引用 • 218 回帖 • 664 关注
  • Node.js

    Node.js 是一个基于 Chrome JavaScript 运行时建立的平台, 用于方便地搭建响应速度快、易于扩展的网络应用。Node.js 使用事件驱动, 非阻塞 I/O 模型而得以轻量和高效。

    139 引用 • 269 回帖 • 1 关注
  • Notion

    Notion - The all-in-one workspace for your notes, tasks, wikis, and databases.

    10 引用 • 80 回帖 • 1 关注
  • sts
    2 引用 • 2 回帖 • 260 关注
  • GitBook

    GitBook 使您的团队可以轻松编写和维护高质量的文档。 分享知识,提高团队的工作效率,让用户满意。

    3 引用 • 8 回帖