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, 运行结果与上一篇博文一致。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值