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 ?
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.
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.
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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With