0

Problem

I am trying to set a header named Cookie. I do this using an interceptor, so that it gets done on every request.

Code

@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);
      })
    );
  }
}

What happens

I always get:

Attempt to set a forbidden header was denied: Cookie

So what can I do here? I also tried setting withCredentials: true directly on every request which also did not work. Is there any other way?

Gh05d
  • 7,923
  • 7
  • 33
  • 64

1 Answers1

2

Some headers are forbidden to be used programmatically for security concerns and to ensure that the user agent remains in full control over them.

Cookie is one of the forbidden header among the list of Forbidden header name list, and hence you cannot set it within the HTTP request header directly from the code.

From docs:

A forbidden header name is the name of any HTTP header that cannot be modified programmatically; specifically, an HTTP request header name

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

You can always set the cookies via document.cookie and browser will automatically send the cookies that matches the criteria. Trying to set cookies to foreign domain will be silently ignored.

Angular comes up with a DOCUMENT DI token which can be used to inject document in a service. You can read more about it how-to-inject-document-in-service.

Siddhant
  • 2,911
  • 2
  • 8
  • 14
  • I tried setting it via `document.cookie` and that seemed to have worked as when I enter that into the browser console. I can only see the name though there, I guess out of security reasons there is no way to see the value, or? Also, can I somehow see the cookie sent on the request? Or is this also not possible? – Gh05d Jan 25 '22 at 09:32
  • 1
    You can check the cookies stored in browser as well as those sent within your Browser dev tools. [Check cookies in Chrome](https://developer.chrome.com/docs/devtools/storage/cookies/) and [Check headers in Chrome](https://developer.chrome.com/docs/devtools/network/#details). Similar way in other browsers too, you should be able to view them. – Siddhant Jan 25 '22 at 09:51