I am new to angular2. My server(spring) responds authentication with a set-cookie value in its response headers.
How to set that cookie to the request headers for the next API calls?
I searched a lot, but I cannot find a suitable solution.
I am new to angular2. My server(spring) responds authentication with a set-cookie value in its response headers.
How to set that cookie to the request headers for the next API calls?
I searched a lot, but I cannot find a suitable solution.
Cookies are automatically attached to every call you make after it is saved for your domain. You are doing something else wrong. In case you want to create automatic mechanism for attaching auth data to REST calls, refere to this tutorial that creates custom HttpInterceptor:
https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462
As part of the http.get()
or http.post()
methods you can specify the RequestOptionsArgs
Use the Headers
in the RequestOptionsArgs
to specify the auth header you need.
As a rough example, see below:
class PeopleComponent {
constructor(http: Http) {
let customHeaders: Headers = new Headers();
customHeaders.append('myHeaderName', 'myHeaderValue');
http.get('http://my.web/service', { headers: customHeaders })
.map(res => res.json())
.subscribe(people => this.people = people);
}
}
Cookies are automatically attached to every call you make after it is saved for your domain. You are doing something else wrong. In case you want to create automatic mechanism for attaching auth data to REST calls, refere to this tutorial that creates custom HttpInterceptor:
https://medium.com/aviabird/http-interceptor-angular2-way-e57dc2842462
In case of a CORS scenario, you will need to add the withCredentials property set to true in the RequestOptions. Below is a snippet on how I've implemented in my HTTP helper:
get(resource: string) {
return this.http.get(`/api/${resource}`, this.getRequestOptions())
.map(result => result.json())
.catch(e => e.status === 401 ? Observable.throw('Unauthorized') : e.json());
}
post(resource: string, body: any) {
return this.http.post(`/api/${resource}`, body, this.getRequestOptions())
.map(result => result.json())
.catch(e => e.status === 401 ? Observable.throw('Unauthorized') : e.json());
}
private getRequestOptions() {
const headers = new Headers({
'Content-Type': 'application/json',
});
return new RequestOptions({headers: headers, withCredentials: true});
}
withCredentials
set, by default it is set to true. no need to define it. –
Nonmetallic © 2022 - 2024 — McMap. All rights reserved.