Angular 5, httpclient ignores set cookie in post

UserMan picture UserMan · Jan 23, 2018 · Viewed 19.2k times · Source

I'm dealing with HttpClient in Angular 5, the problem is the cookie sent by the server during login process, it seems that Angular is ignoring it because next request with "withCredentials" is not setting it.

My package.json

.... "@angular/cli": "1.6.3", "@angular/compiler-cli": "^5.0.0", "@angular/language-service": "^5.0.0", ....

my code

makeLogin (us:string, password:string): Observable<any> {
    let body : any = new HttpParams()
      .set('username', us)
      .set('password', password);
    return this.http.post(this.urlLogin,
      body.toString(),

      {
        headers: new HttpHeaders()
          .set('Content-Type', 'application/x-www-form-urlencoded')
      }
    );
  }

Server returns http 200 with these headers

Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:4200
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:17
Date:Tue, 23 Jan 2018 21:05:46 GMT
Expires:0
Pragma:no-cache
Set-Cookie:JSESSIONID=BF9392ED5DE99710B44845201DD26B3F;path=/;HttpOnly
Vary:Origin
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

After that, next request for example

getEventt (): Observable<any> {
    return this.http.get('http://localhost:8080/list',{ withCredentials: true });
  }

Using chrome or firefox developer tools I can't see the cookie sent, but If I use browser or postman everything works fine and I can see the cookie been sent.

I don't know if I'm doing something wrong or maybe using httpClient in a bad way.

If it helps, server is deployed on tomcat 8, and Angular app is running on nodejs (npm start)

Answer

UserMan picture UserMan · Jan 24, 2018

Finally I was able to made it work!!

The solution was in post request,

Maybe I'm wrong but it seems like RequestOptions class was deprecated in Angular 5.0.0, so after several attempts hit the right configuration, Here is the method fixed

/** POST: add a new hero to the server */
makeLogin (us:string, password:string): Observable<any> {
    let enco : any = new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded');

    let body : any = new HttpParams()
    .set('username', us)
    .set('password', password);
    return this.http.post(this.urlServicioLogin,
     body.toString(),
     {
       headers: enco,withCredentials:true
     }
   );
}

Now with withCredentials true I can see in browsers the cookie being set, and after that send it with subsequent requests.

Note: If the app has to consume a rest service where auth is made with cookies ALL interactions with backend will need withCredentials flag set to true.