Angular + Spring Boot - 无法通过 HTTPS 发送 cookie



我有一个Angular 12前端应用程序与Spring Boot后端应用程序通信。API应该使用cookie传递CSRF令牌,但我的逻辑似乎只适用于localhost。

请找到以下代码片段:

  • 通过ngx cookie服务设置的角度cookie:
this.cookieService.set(key, value, {
secure: environment.apiHost.startsWith('https'),
sameSite: environment.apiHost.startsWith('https') ? 'None' : undefined
});
  • 在每个请求之前调用的角度拦截器:
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
// Handle cookies
request = request.clone({
withCredentials: true
});
return next.handle(request).pipe(
...
);
}
  • Spring Boot CORS常规配置:
List<String> allowedOrigins = new ArrayList<>();
allowedOrigins.add("http://localhost:4200");
allowedOrigins.add("https://<host_name_not_localhost>");
config.setAllowCredentials(true);
config.setAllowedOrigins(allowedOrigins);
config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept"));
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH"));
source.registerCorsConfiguration("/api/**", config);
return new CorsFilter(source);

老实说,我不明白问题是在前端还是在后端。。。同样,通过HTTP(localhost(发送Cookie工作正常,而在HTTPS上调试调用时不会出现Cookie属性。

你对此有什么建议吗?

提前谢谢。

这里唯一的原因可能是在创建cookie时,您没有将域设置为后端的域。你可以做一些类似的事情

var cookieName = 'HelloWorld';
var cookieValue = 'HelloWorld';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate 
+ ";domain=.example.com;path=/";

在上面的例子中,example.com是您的后端域。或者通过使用cookie api,请参阅此处:-https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_the_Cookies_API

我决定去掉cookie,并在请求头中传递信息,这似乎是一种更安全的方法。另外,我可以从后端本身控制允许的头。

最新更新