保持角度为4.3的会话cookie

时间:2017-08-16 04:20:17

标签: angular

我尝试对spring boot后端进行身份验证并获取一些数据

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();

身份验证工作正常。这是响应头:

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

然后我尝试从春季启动项目。这是我的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

它没有使用会话cookie,所以它会抛出一个错误,说不识别。

如何使用棱角4.3修复此问题?

1 个答案:

答案 0 :(得分:5)

如果您在Angular 4.3中使用新的HttpClient模块,您是否尝试在第二个(选项)参数中将withCredentials设置为true

constructor(private http: HttpClient) {

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

}

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