美文网首页编程技术
Spring Boot + Spring Security解决P

Spring Boot + Spring Security解决P

作者: 吴俊达 | 来源:发表于2017-03-22 15:15 被阅读9227次

以下配置基于spring boot版本1.4.2.RELEASE,默认引入的spring security版本为4.1.3.RELEASE,页面模板采用thymeleaf。

问题现象:
HTTP Status 403-Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.

关于CSRF的描述,此处不再赘述,解决方案如下。
第1、2、3种方案测试通过,第四种方式未做测试。

1.定义headers,post方式提交的时候带上headers的信息。

var headers = {};
headers['X-CSRF-TOKEN'] = "[[${_csrf.token}]]";
$.ajax({
    url: url,
    type: "POST",
    headers: headers,
    dataType: "json",
    success: function(result) {
    }
});

2.直接作为参数提交。

$.ajax({
    url: url,
    data: {
        "[[${_csrf.parameterName}]]": "[[${_csrf.token}]]"
        },
    type: "POST",
    dataType: "json",
    success: function(result) {
    }
});

3.form提交的时候,如果出现csrf问题,可将该参数作为隐藏项。跟第二种方式类似。

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">

4.在 @EnableWebSecurity配置中,禁用CSRF。

http.csrf().disable();

相关文章

网友评论

  • 81acca886333:抄来抄去。。
  • 9dc8703d6f98:为啥我4.在 @EnableWebSecurity配置中,没有禁用CSRF。
  • Andy_b37f:请问博主springboot如何集成csrf的?我百度没有这方面的资料。
    心尘宁静:这个不是springboot的 这个是springsecurity的,springsecurity默认是开启 csrf 的,对于ajax post请求很蛋疼的

本文标题:Spring Boot + Spring Security解决P

本文链接:https://www.haomeiwen.com/subject/rsponttx.html