【问题标题】:Angular + Spring Boot - Can't send cookies over HTTPSAngular + Spring Boot - 无法通过 HTTPS 发送 cookie
【发布时间】:2022-02-16 17:15:09
【问题描述】:

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

请找到以下sn-ps的代码:

  • 通过 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 调试调用时不显示属性。

您对此有什么建议吗?

提前谢谢你。

【问题讨论】:

  • 后端托管的域是否与前端不同?
  • 您好,前端和后端应用的域是一样的。

标签: java angular spring-boot cookies ngx-cookie-service


【解决方案1】:

这里的唯一原因可能是在创建 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

【讨论】:

  • 嗨,这实际上是不正确的:cookie 在浏览器中正确设置,具有相同的后端域。此外,它们存储为“安全”,并且“无”作为 SameSite 属性。唯一的区别是路径:BE在域后有“DTM-BE”,而cookies设置为“tbx-app”作为路径。 IE。 https:///DTM-BE/api/...是BE,而cookie有域和路径“/tbx-app”。
  • 你确定你使用的拦截器在生产中吗?
  • 请检查 cookie 是否有有效路径且未过期。
  • 拦截器工作正常,因为它也处理错误并且错误显示正确。从代码中可以看出,当前未设置过期时间,因此它们被存储为“会话”cookie。我不认为这是问题......
  • 并且您没有在请求标头中获取 cookie?
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 2016-02-25
    • 2018-09-11
    • 2014-10-09
    • 2017-02-09
    • 1970-01-01
    • 2017-08-11
    相关资源
    最近更新 更多