Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send "Cookie" in request header for all the requests in Angular2?

Tags:

angular

Actually , our backend authenticate the request using Cookie in the request header. I know that it will refuse if I set a header "Cookie". So , is there a way to send a Cookie to the back end ?

like image 856
ad3 Avatar asked Feb 24 '16 12:02

ad3


People also ask

How do I send a cookie request in header?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons.

Is cookie in request header?

A cookie is an HTTP request header i.e. used in the requests sent by the user to the server. It contains the cookies previously sent by the server using set-cookies. It is an optional header.

How do I put cookies in GET request?

To add cookies to a request for authentication, use the header object that is passed to the get/sendRequest functions. Only the cookie name and value should be set this way. The other pieces of the cookie (domain, path, and so on) are set automatically based on the URL the request is made against.


1 Answers

I guess that there is a phase where you ask the server to authenticate you. Following this (and if the authentication is successful), the server will return a cookie in the response. The browser will store this cookie and send it again for each call.

That said, in the case of cross domain requests (CORS), you need to set the withCredentials of XHR to true to make the browser add cookies in your requests.

To enable this with Angular2, we need to extend the BrowserXhr class as described below:

@Injectable() export class CustomBrowserXhr extends BrowserXhr {   constructor() {}   build(): any {     let xhr = super.build();     xhr.withCredentials = true;     return <any>(xhr);   } } 

and override the BrowserXhr provider with the extended:

bootstrap(AppComponent, [   HTTP_PROVIDERS,   provide(BrowserXhr, { useClass: CustomBrowserXhr }) ]); 

See this questions for more details:

  • Set-cookie in response not set for Angular2 post request
  • xmlhttprequest and set-cookie & cookie

Edit (following the freaker's comment)

From RC2, you can use the withCredentials property directly within the request configuration as described below:

this.http.get('http://...', { withCredentials: true }) 

Edit (following the [maxou] comment)

Remember to include withCredentials: true on every request.

like image 110
Thierry Templier Avatar answered Sep 16 '22 17:09

Thierry Templier