我正在尝试在Spring Boot API之上构建一个Angular 2页面 . 我已经配置了CORS(正确的我相信),但我被Spring Security的CSRF保护所阻止 .
据我所知,Angular 2自RC2起自动处理CSRF,而我在RC4上 . 服务器正在发送XSRF令牌以响应客户端的POST,如下所示:
我认为Angular 2没有把它拿起来?我知道CORS正在工作,因为当我把 .ignoringAntMatchers("/urlhere/") 放在 .csrf() 的末尾进行测试时,请求就完成了,所以CORS没有阻止它 . 这是我的HttpSecurity配置方法:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/auth/**", "/signup/**").permitAll()
.and()
.headers()
.and()
.exceptionHandling()
.and()
.cors()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
我在客户端的登录过程包括一个首先发送凭据,然后使用JWT令牌检索凭据的方法 . 这两种方法如下:
sendCredentials(model) {
let tokenUrl = 'http://localhost:8080/user/login';
let headers1 = new Headers({'Content-Type': 'application/json'});
return this.http.post(tokenUrl, JSON.stringify(model), {headers: headers1});
}
sendToken(token){
let userUrl = 'http://localhost:8080/rest/user/users';
let headers2 = new Headers({'Authorization': 'Bearer '+token});
return this.http.get(userUrl, {headers:headers2});
}
为了满足CSRF保护的要求,我缺少什么?是客户端吗?或者我需要将 /login/ 添加到我的antMatchers列表中?
1 回答
我知道现在已经很晚了,我遇到了同样的问题并设法解决了 . 角度http请求中的问题:
您需要将其调整为发送方式:
您必须为所有http请求添加
withCredentials: true
. 你为什么需要它?每次向Spring(服务器)发送http请求(OPTIONS,POST等)时,它都会生成新的XSRF-TOKEN并将其发送给客户端,withCredentials: true
将在浏览器中保存这个新的XSRF-TOKEN,以后用于新的http请求,所以如果你的一个http请求没有withCredentials: true
,它将简单地忽略新的XSRF-TOKEN并使用旧的(过期的)XSRF-TOKEN来获取http请求 .