Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a cookie header with Angular 5

I'm currently attempting to set a Cookie header with the following HTTPInterceptor:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private cookieService: CookieService ) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      setHeaders: {
        'Cookie': 'session=' + this.cookieService.get('session'),
        'withCredentials': 'true',
      }
    });
    return next.handle(request);
  }

}

When attempting to set the Cookie I get the following error:

Refused to set unsafe header "Cookie"

I'm making the request to a local Flask API.

I have attempted to manually set the headers with HTTPHeaders like here and also tried to set xhr2.prototype._restrictedHeaders.cookie = false; shown here. All to no avail. Any idea how I can set the cookie?

like image 405
Harpal Avatar asked Aug 30 '25 15:08

Harpal


1 Answers

So I found the solution to my question, hopefully this will help others with the same problem. It turns out I was setting withCredentials incorrectly and should be set as follows:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private cookieService: CookieService ) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    request = request.clone({
      withCredentials: true,
    });
    return next.handle(request);
  }

}

When it is set like this, angular will automatically find the associated cookies and send them with the request

like image 84
Harpal Avatar answered Sep 02 '25 15:09

Harpal