SpringSecurity自定义过滤器

「这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战」。

前言

SpringSecurity的核心就是一组过滤器链,框架本身给我们提供了一些默认的安全过滤器,但是结合现实开发场景,我们也可以自定义过滤器,加入过滤器链中,来支撑我们的业务需求,最常见的就是验证码逻辑了。

图形验证码

实现思路就是在校验用户名和密码前加上一层过滤,验证码校验,通过请求获取图形验证码,请求成功的同时将验证码明文信息保存在session中,用于后面的校验,校验成功后走后面的逻辑。

一、准备配置

为工程引用依赖

<dependency>
    <groupId>cloud.agileframework</groupId>
    <artifactId>spring-boot-starter-kaptcha</artifactId>
    <version>2.0.0</version>
</dependency>
复制代码
  • 配置一个kaptcha实例
  • WebSecurityConfig里添加

这里不做详细介绍,可查阅相关资料了解

@Bean
public Producer kaptcha() {
    //配置图形验证码的基本参数
    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;
}
复制代码
  • 创建一个CaptchaControlle用于获取图形验证码
@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 capImage = captchaProducer.createImage(capText);
        //获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        //将图片验证码数据写到响应输出流
        ImageIO.write(capImage, "jpg", outputStream);
        //推送并关闭响应输出流
        try {
            outputStream.flush();
        } finally {
            outputStream.close();
        }
    }
}
复制代码

二、自定义图形验证码校验过滤器

通过继承OncePerRequestFilter来实现,它可以保证一次请求只通过一次该过滤器

1. 自定义校验异常类

  • 创建异常包exception
  • 继承AuthenticationException
/**
 * 验证码校验失败异常
 */
public class VerificationCodeException extends AuthenticationException {
    public VerificationCodeException(String msg) {
        super(msg);
    }
}
复制代码

2. 自定义异常处理handler

  • 创建处理器包handler
  • 实现AuthenticationFailureHandler
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(401);
        PrintWriter out = httpServletResponse.getWriter();
        out.write("{\n" +
                "    \"error_code\": 401,\n" +
                "    \"error_name\":" + "\"" + e.getClass().getName() + "\",\n" +
                "    \"message\": \"请求失败," + e.getMessage() + "\"\n" +
                "}");
    }
}
复制代码

3. 自定义校验验证码过滤器

  • 创建过滤器包filter
  • 继承OncePerRequestFilter
public class VerificationCodeFilter extends OncePerRequestFilter {

    private final AuthenticationFailureHandler authenticationFailureHandler = new MyAuthenticationFailureHandler();

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //非登录请求不校验验证码
        String requestURI = httpServletRequest.getRequestURI();
        if (!"/myLogin".equalsIgnoreCase(httpServletRequest.getRequestURI())) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        } else {
            try {
                verificationCode(httpServletRequest);
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            } catch (VerificationCodeException e) {
                System.out.println(e);
                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
            } catch (ServletException e) {
                e.printStackTrace();
            }
        }
    }

    private void verificationCode(HttpServletRequest httpServletRequest) throws VerificationCodeException {
        String captcha = httpServletRequest.getParameter("captcha");
        HttpSession session = httpServletRequest.getSession();
        String captchaCode = (String) session.getAttribute("captcha");
        if (StringUtils.isNotEmpty(captchaCode)) {
            // 校验过一次后清除验证码,不管成功或失败
            session.removeAttribute("captcha");
        }
        //校验不通过抛出异常
        if (StringUtils.isEmpty(captcha) || StringUtils.isEmpty(captchaCode) || !captcha.equals(captchaCode))
            throw new VerificationCodeException("图形验证码校验异常");
    }
}
复制代码

4. 修改配置configure

  • 放行请求验证码api/captcha.jpg
  • 添加验证失败处理
  • 将过滤器添加在UsernamePasswordAuthenticationFilter之前
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/api/**").hasRole("ADMIN")
                .antMatchers("/user/api/**").hasRole("USER")
                .antMatchers("/app/api/**","/captcha.jpg").permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/myLogin.html")
                // 指定处理登录请求的路径,修改请求的路径,默认为/login
                .loginProcessingUrl("/mylogin").permitAll()
                .failureHandler(new MyAuthenticationFailureHandler())
                .and()
                .csrf().disable();
        //将过滤器添加在UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(new VerificationCodeFilter(), UsernamePasswordAuthenticationFilter.class);
    }
复制代码

三、登录页面

篇幅有限,这里不贴出完整代码了,有需要留邮箱发送代码,其实也比较简单。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>登录</title>
</head>
<body>
<div class="main">
    <div class="title">
        <span>密码登录</span>
    </div>

    <div class="title-msg">
        <span>请输入登录账户和密码</span>
    </div>

    <form class="login-form" action="/mylogin" method="post" novalidate>
        <!--输入框-->
        <div class="input-content">
            <!--autoFocus-->
            <div>
                <input type="text" autocomplete="off"
                       placeholder="用户名" name="username" required/>
            </div>

            <div style="margin-top: 16px">
                <input type="password"
                       autocomplete="off" placeholder="登录密码" name="password" required maxlength="32"/>
            </div>
            <div style="margin-top: 16px;display: flex">
            <!-- 新增图形验证码输入框  -->
                <input type="text" name="captcha" placeholder="验证码" width="180px" />
                <img src="/captcha.jpg" alt="captcha" height="42px" width="150px" style="margin-left: 20px">
            </div>
        </div>
        <!--登入按钮-->
        <div style="text-align: center">
            <button type="submit" class="enter-btn">登录</button>
        </div>

        <div class="foor">
            <div class="left"><span>忘记密码 ?</span></div>

            <div class="right"><span>注册账户</span></div>
        </div>
    </form>
</div>
</body>
复制代码

四、测试

  • 启动项目
  • 访问api:http://localhost:8080/user/api/hi

image-20201019160019522.png

  • 输入正确用户名密码,正确验证码
  • 访问成功
  • 页面显示hi,user.
  • 重启项目
  • 输入正确用户名密码,错误验证码
  • 访问失败
  • 返回失败报文
{
"error_code": 401,
"error_name": "com.yang.springsecurity.exception.VerificationCodeException",
"message": "请求失败,图形验证码校验异常"
}
复制代码