0

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

请找到以下代码片段:

  • 通过 ngx-cookie-service 设置 Angular cookie:
this.cookieService.set(key, value, {
   secure: environment.apiHost.startsWith('https'),
   sameSite: environment.apiHost.startsWith('https') ? 'None' : undefined
});
  • 在每个请求之前调用 Angular 拦截器:
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 工作正常,而在调试调用时没有出现Cookie属性HTTPS。

你对此有什么建议吗?

先感谢您。

4

2 回答 2

0

这里的唯一原因可能是在创建 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 是您的后端域。或使用 cookies api,请参阅此处:- https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Work_with_the_Cookies_API

于 2022-02-15T15:59:51.303 回答
0

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

于 2022-02-16T09:15:09.133 回答