Set Cookie in Request Headers Angular2
Asked Answered
N

3

12

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.

Nonmetallic answered 13/4, 2017 at 11:18 Comment(2)
Cookies are automatically appended to requests. Why do you want to add it to headers as well?Revolting
@JánHalaša I wasn't very clear on that part of the question either. I'm thinking maybe there's some confusion here between what the headers are doing and what the cookies are doing.Saffian
L
5

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

Lucifer answered 13/4, 2017 at 11:41 Comment(6)
Actually, I followed everything correctly and I tried everything ..but no use. angular2 does not stores cookie by defaultNonmetallic
It is not Angular's job to save cookies, browser does that for you. But strange that it doesn't do that. Than use this for cookies management github.com/BCJTI/ng2-cookies/blob/master/README.MDLucifer
@SibiRaj cookies are nothing to do with Angular - the server sends them back with a request and any subsequent request to that server will send them up again. You should have a look at what's actually happening with your cookies - cookies are the right way to do what you're looking for. Headers will work, but it's not advised.Saffian
@MarioPetrovic... ThanksNonmetallic
@SibiRaj can you tell please write down your server misconfiguration details? I am facing the same issue.Commissioner
Sorry. I moved to another project. I don't have any information on the server. But that is nothing but that is nothing but a simple spring app with authentication. You could google that.Nonmetallic
S
11

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);
  }
}
Saffian answered 13/4, 2017 at 11:22 Comment(1)
I've added a code sample but I'd recommend investigating whether you actually need to do anything specific with the headers - as mentioned by others, the cookies are usually sent back to the server automatically with each request, so you should be able to inspect them server-sideSaffian
L
5

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

Lucifer answered 13/4, 2017 at 11:41 Comment(6)
Actually, I followed everything correctly and I tried everything ..but no use. angular2 does not stores cookie by defaultNonmetallic
It is not Angular's job to save cookies, browser does that for you. But strange that it doesn't do that. Than use this for cookies management github.com/BCJTI/ng2-cookies/blob/master/README.MDLucifer
@SibiRaj cookies are nothing to do with Angular - the server sends them back with a request and any subsequent request to that server will send them up again. You should have a look at what's actually happening with your cookies - cookies are the right way to do what you're looking for. Headers will work, but it's not advised.Saffian
@MarioPetrovic... ThanksNonmetallic
@SibiRaj can you tell please write down your server misconfiguration details? I am facing the same issue.Commissioner
Sorry. I moved to another project. I don't have any information on the server. But that is nothing but that is nothing but a simple spring app with authentication. You could google that.Nonmetallic
D
4

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});
}
Dropline answered 11/7, 2017 at 12:18 Comment(1)
thanks. now with latest angular version. it even works without withCredentials set, by default it is set to true. no need to define it.Nonmetallic

© 2022 - 2024 — McMap. All rights reserved.