【问题标题】:Cannot set Header Cookie in Angular even when passing withCredentials: true即使在传递 withCredentials 时也无法在 Angular 中设置 Header Cookie:true
【发布时间】:2022-01-25 13:44:17
【问题描述】:

问题

我正在尝试设置一个名为 Cookie 的标头。我使用拦截器执行此操作,以便在每次请求时完成。

代码

@Injectable
export class HeaderInterceptor implements HttpInterceptor {
  constructor(private: authService: AuthenticationService) {}

  intercept(reg: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  return from(this.authService.getAuthentication()).pipe(
    switchMap((token) => {
      const headers = req.headers
        .set(TOKEN, "someToken")
        .set("Cookie", "someCookie")
        .append("Content-Type", "application/json")
        .append("Accept", "application/json");

      const requestClone = req.clone({ headers, withCredentials: true });
      return next.handle(requestClone);
      })
    );
  }
}

会发生什么

我总是得到:

尝试设置禁止的标头被拒绝:Cookie

那么我可以在这里做什么?我还尝试在每个请求上直接设置withCredentials: true,但这也不起作用。有没有其他办法?

【问题讨论】:

    标签: javascript angular http cors http-headers


    【解决方案1】:

    出于安全考虑并确保用户代理保持对它们的完全控制,禁止以编程方式使用某些标头。

    CookieForbidden header name 列表中的禁止标头之一,因此您不能直接在代码中将其设置在 HTTP 请求标头中。

    来自docs

    禁止的标头名称是任何不能以编程方式修改的 HTTP 标头的名称;具体来说,一个 HTTP 请求标头名称

    规格: https://fetch.spec.whatwg.org/#forbidden-header-name

    您可以随时通过document.cookie 设置cookies,浏览器会自动发送符合条件的cookies。尝试将 cookie 设置为外部域将被忽略。

    Angular 提供了一个DOCUMENT DI 令牌,可用于在服务中注入文档。你可以阅读更多关于它的信息how-to-inject-document-in-service

    【讨论】:

    • 我尝试通过document.cookie 设置它,当我将它输入浏览器控制台时,它似乎已经起作用了。虽然在那里我只能看到名字,我猜出于安全原因没有办法看到价值,或者?另外,我能以某种方式看到请求中发送的 cookie 吗?还是这也不可能?
    • 您可以检查存储在浏览器中的 cookie 以及在您的浏览器开发工具中发送的那些。 Check cookies in ChromeCheck headers in Chrome。在其他浏览器中也是类似的方式,您应该能够查看它们。
    猜你喜欢
    • 2017-01-01
    • 2021-06-15
    • 2020-04-18
    • 2019-05-07
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    相关资源
    最近更新 更多