0
点赞
收藏
分享

微信扫一扫

Spring Security - 实现图形验证码(一)

Java架构领域 2021-09-28 阅读 83

Spring Security - 使用过滤器实现图形验证码

实现思路就是在校验用户名和密码前加上一层过滤,验证码校验,通过请求获取图形验证码,请求成功的同时将验证码明文信息保存在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>
<style>
    body {
        background: #353f42;
    }

    * {
        padding: 0;
        margin: 0;
    }

    .main {
        margin: 0 auto;
        padding-left: 25px;
        padding-right: 25px;
        padding-top: 15px;
        width: 350px;
        height: 400px;
        background: #FFFFFF;
        /*以下css用于让登录表单垂直居中在界面,可删除*/
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -175px;
        margin-left: -175px;
    }

    .title {
        width: 100%;
        height: 40px;
        line-height: 40px;
    }

    .title span {
        font-size: 18px;
        color: #353f42;
    }

    .title-msg {
        width: 100%;
        height: 64px;
        line-height: 64px;
    }

    .title:hover {
        cursor: default;
    }

    .title-msg:hover {
        cursor: default;
    }

    .title-msg span {
        font-size: 12px;
        color: #707472;
    }

    .input-content {
        width: 100%;
        height: 180px;
    }

    .input-content input {
        width: 330px;
        height: 40px;
        border: 1px solid #dad9d6;
        background: #ffffff;
        padding-left: 10px;
        padding-right: 10px;
    }

    .enter-btn {
        width: 350px;
        height: 40px;
        color: #fff;
        background: #0bc5de;
        line-height: 40px;
        text-align: center;
        border: 0px;
    }

    .foor {
        width: 100%;
        height: auto;
        color: #9b9c98;
        font-size: 12px;
        margin-top: 20px;
    }

    .enter-btn:hover {
        cursor: pointer;
        background: #1db5c9;
    }

    .foor div:hover {
        cursor: pointer;
        color: #484847;
        font-weight: 600;
    }

    .left {
        float: left;
    }

    .right {
        float: right;
    }
</style>
</html>

四、测试

启动项目

访问api:http://localhost:8080/user/api/hi

输入正确用户名密码,正确验证码

访问成功

页面显示hi,user.

重启项目

输入正确用户名密码,错误验证码

访问失败

返回失败报文

{
"error_code": 401,
"error_name": "com.yang.springsecurity.exception.VerificationCodeException",
"message": "请求失败,图形验证码校验异常"
}
举报

相关推荐

0 条评论