我在单页应用程序中使用 spring boot、spring rest 和 spring security。
在 spring 4 中,CSRF 默认启用。
我写了一个扩展 WebSecurityConfigureAdapter 的类
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/rest/**").authenticated();
http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
http.formLogin().successHandler(authenticationSuccessHandler);
http.formLogin().failureHandler(authenticationFailureHandler);
http.logout().logoutSuccessUrl("/");
// tried with and without... same issue
http.addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class);
}
CsrfTokenResponseHeaderBindingFilter 来自 https://github.com/aditzel/spring-security-csrf-filter/blob/master/src/main/java/com/allanditzel/springframework/security/web/csrf/CsrfTokenResponseHeaderBindingFilter.java
我只使用html(所以没有jsp,没有xhmtl ...)页面。我做ajax调用并提供我的html。
请求头
POST /login HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 30
Pragma: no-cache
Cache-Control: no-cache
Accept: */*
Origin: http://localhost:8080
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate
Accept-Language: fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4
Cookie: JSESSIONID=B05ED2676EC1637D74AC7622E018C9FD
在我的表格中,我有
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
当我尝试登录时,我得到
{"timestamp":1444179957867,"status":403,"error":"Forbidden","message":"Expected CSRF token not found. Has your session expired?","path":"/login"}
当日志失败时,该命令返回null
jqXHR.getResponseHeader('X-CSRF-TOKEN')
ajax 调用
var data = 'username=' + $('#username').val() + '&password=' + $('#password').val();
$.ajax({
data: data,
timeout: 1000,
type: 'POST',
url: '/login'
}).done(function (data, textStatus, jqXHR) {
window.location = "main.html";
}).fail(function (jqXHR, textStatus, errorThrown) {
});
});
编辑
当我连接到 localhost:8080 时,在浏览器中。
我在标题答案中看到
X-CSRF-HEADER:X-CSRF-TOKEN
X-CSRF-PARAM:_csrf
X-CSRF-TOKEN:0d5bf042-a30f-4f2e-a99c-51ed512f811a
如何在 JS 中获取这些信息?我需要把它放在我的电话后。