Spring security下csrf token的认证

在上一篇博文《Springboot 1.5.1整合Spring security 4》中,我们碰到“Could not verify the provided CSRF token because your session was not found. ”错误, 经过分析,是因为我们成功登录后,spring security为了防止CSRF攻击,需要在每个页面中验证成功登录后创建的csrf token值,而我们在静态页面中又无法传递这个token, 今天我们将来说明下如何处理这个问题。
还是基于上篇博文的代码,由于我们在页面上需要动态获取csrf token, 这时我们可以在页面上引入JS 代码,使之成为动态网页。
1) 将http.csrf().disable();注释掉

@Override
    protected void configure(HttpSecurity http) throws Exception {
        //http.csrf().disable();
        http.authorizeRequests()
                        .antMatchers("/", "/springbootbase").permitAll()
                        .anyRequest().authenticated()
                        .and()
                    .formLogin()
                        .loginPage("/login")
                        .failureUrl("/login?error")
                        .permitAll() //5
                        .and()
                    .logout().permitAll();
    }

2) 将index.html 改成JSP 文件: index.jsp
将csrf token 作为表单的隐藏域一起提交即可解决

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <title>Hello World!</title>
</head>
<body>
    <h1 th:inline="text">Hello World</h1>
    <form th:action="@{/logout}" action="./logout" method="post">
        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
        <input type="submit" value="Sign Out"/>
    </form>
</body>
</html>

3) 重启tomcat server, 运行结果与上一篇博文一致。

猜你喜欢

转载自blog.csdn.net/laputa_sky/article/details/80041557
今日推荐