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?
Advertisement
Answer
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.