gpt4 book ai didi

java - Angular 2/Spring Security CSRF 实现问题

转载 作者:太空狗 更新时间:2023-10-29 18:33:39 27 4
gpt4 key购买 nike

我正在尝试在 Spring Boot API 之上构建 Angular 2 页面。我已经配置了 CORS(我相信是正确的),但是我被 Spring Security 的 CSRF 保护阻止了。

据我了解Angular 2 handles CSRF automatically从 RC2 开始,我在 RC4 上。服务器正在发送 XSRF token 以响应来自客户端的 POST,如下所示:

enter image description here

我假设 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 token 检索凭据。两种方法如下:

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 列表中吗?

最佳答案

我知道已经晚了,但我遇到了同样的问题并设法解决了。 Angular http 请求中的问题:

return this.http.post(tokenUrl, JSON.stringify(model), {headers: headers1});

您需要将其调整为这样发送:

return this.http.post(tokenUrl, JSON.stringify(model), {headers: headers1, withCredentials: true});

您必须将 withCredentials: true 添加到您的所有 http 请求中。你为什么需要它?每次您向 Spring(服务器)发送 http 请求(OPTIONS、POST 等)时,它都会生成新的 XSRF-TOKEN 并将其发布给客户端,withCredentials: true 会将这个新的 XSRF-TOKEN 保存在浏览器中并稍后用于新的 http 请求,因此如果您的一个 http 请求没有 withCredentials: true,它将简单地忽略新的 XSRF-TOKEN 并使用旧的(过期的)XSRF-TOKEN 进行 http 请求.

关于java - Angular 2/Spring Security CSRF 实现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38929045/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com