在spring mvc showcase中使用了CSRF,在home.jsp中 有这样的标准做法:
<!--
Used for including CSRF token in JSON requests
Also see bottom of this file for adding CSRF token to JQuery AJAX requests
-->
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
......
$("meta[name='_csrf']").attr("content");
var token = "hello";
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function(e, xhr, options) {
xhr.setRequestHeader(header, token);
});
但是我发现,即便我在token中 乱写一个,或者部分,请求仍然能收到正常响应,请问是我对CSRF理解错了么? 如果我乱写一个,应该返回错误才对啊!
ok,自己解决了。
Spring security 默认的org.springframework.security.web.csrf.CsrfFilter 对于HTTP请求有如下的判断:
private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
因此如果我改成hello之后,必须要通过put或者post请求才能测试的出来。
很多讲CSRF原理的文章,使用的是GET来进行举例,Spring Security的实现上有这样的不同,导致我查了半天。