Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping session cookie with angular 4.3

Tags:

angular

I'm trying to authenticate to a spring boot back-end and get some data

this.http.get(`${this.configService.api}user`, {
        headers: new HttpHeaders().set('Authorization', "Basic " + btoa(user.login + ":" + user.password)),
      }).toPromise().then(resp => {
        this.http.get(`${this.configService.api}projects`).toPromise();

The authentication works fine. Here is the response header:

HTTP/1.1 200
Access-Control-Allow-Origin: http://localhost:4200
Vary: Origin
Access-Control-Allow-Credentials: true
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
Set-Cookie: JSESSIONID=5C698E29D0DD942ED36AF2D93287B03B; Path=/; HttpOnly
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Wed, 16 Aug 2017 04:02:42 GMT

Then I try to get the project from spring boot. Here is the header of my HTTP GET:

GET /user HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Accept: application/json, text/plain, */*
Origin: http://localhost:4200
Authorization: Basic dXNlcjpwYXNzd29yZA==
User-Agent: Mozilla/5.0 ...
DNT: 1
Referer: http://localhost:4200/auth
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8,fr;q=0.6

It doesn't use the session cookie so it throws a error saying no identification.

How do I fix this with angular 4.3?

like image 926
tbo47 Avatar asked Aug 16 '17 04:08

tbo47


1 Answers

In Angular version >= 4.3

If you are using the new HttpClient module in Angular 4.3, did you try to set withCredentials to true in the second (options) parameter ?

constructor(private http: HttpClient) {

  this.http.get('/my/resource/url', {withCredentials: true})
    .subscribe(result => {
      ...
    });

}

Source : https://angular.io/api/common/http/HttpClient#get

like image 124
eroak Avatar answered Sep 29 '22 09:09

eroak