首页 > 解决方案 > Couchdb _session POST 未从 Angular 7 应用程序返回 Chrome 中的 set-cookie 标头

问题描述

我有一个 Angular 7 应用程序向 couchDb _sessions api 发出 POST 请求以进行身份​​验证。根据文档,我应该在响应标头中有一个 set-cookie 标头,但没有 set-cookie 标头。

这是响应的样子:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:5800
Access-Control-Expose-Headers: content-type, cache-control, accept-ranges, etag, server, x-couch-request-id, x-couch-update-newrev, x-couchdb-body-time
Cache-Control: must-revalidate
Connection: keep-alive
Content-Length: 46
Content-Type: application/json
Date: Mon, 10 Jun 2019 20:21:53 GMT
Server: nginx/1.10.3 (Ubuntu)

但是如果我通过 curl 发送相同的请求:

curl -v https://example.org/_session -H "Content-Type:application/json
" -d '{"name":"user","password":"password"}'

这就是我得到的:

< HTTP/1.1 200 OK
< Server: nginx/1.10.3 (Ubuntu)
< Date: Mon, 10 Jun 2019 20:25:54 GMT
< Content-Type: application/json
< Content-Length: 46
< Connection: keep-alive
< Cache-Control: must-revalidate
< Set-Cookie: AuthSession=c2JxMTIzOjVDRkVCQ0QyOvjMZQhdhyUqRjmDjl_Hipiz7hxa; Version=1; Expires=Mon, 10-Jun-2019 20:35:54 GMT; Max-Age=600; Path=/; HttpOnly
<
{ [46 bytes data]
100    87  100    46  100    41     46     41  0:00:01 --:--:--  0:00:01   154{"ok":true,"name":"username","roles":["sales"]}

我也尝试将 { withCredentials: true} 放在标题中,但我仍然没有得到任何 cookie。cookie 也不存在于 chrome dev-tools 应用程序选项卡和浏览器的 cookie 部分中。

    const _httpHeaders = new HttpHeaders();
    const headers = _httpHeaders.append('withCredentials', 'true');
    console.log(headers);
    return this._httpService.doAsyncTask(AppConstants.LOGIN_URL, 'POST', data, {headers});

我怎样才能找到解决方案?

标签: authenticationpostcookiescouchdbangular7

解决方案


使用Basic Authorization标题,withCredentials: true应该可以工作。

let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.set('Accept', 'application/json');
httpHeaders = httpHeaders.set('Content-type', 'application/json');
httpHeaders = httpHeaders.set('Authorization', 'Basic ' + btoa(user + ':' + password));
const options = { headers: httpHeaders, withCredentials: true };

this._httpService.doAsyncTask(AppConstants.LOGIN_URL, 'POST', data, options);

btoa()以 base-64 编码用户/密码。该data对象不应再次包含凭据。


推荐阅读