【问题标题】:Couchdb _session POST not returning set-cookie header in Chrome from Angular 7 appCouchdb _session POST 未从 Angular 7 应用程序返回 Chrome 中的 set-cookie 标头
【发布时间】:2019-06-10 12:30:56
【问题描述】:

我有一个 Angular 7 应用程序向 couchDb _sessions api 发出 POST 请求以进行身份​​验证。根据documentation,我应该在响应标头中有一个 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 发送相同的请求:

卷曲 -v https://example.org/_session -H “内容类型:应用程序/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});

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

【问题讨论】:

    标签: authentication post cookies couchdb angular7


    【解决方案1】:

    使用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 对象不应再次包含凭据。

    【讨论】:

    • 非常感谢@uminder,它就像一个魅力。但是,我遇到了另一个问题,即即使在使用 withCredentials: true 之后,浏览器也没有在 GET _sessions api 的标头中为后续请求设置 cookie。我会进行更多研究并告诉你。
    猜你喜欢
    • 1970-01-01
    • 2013-05-30
    • 2015-09-12
    • 1970-01-01
    • 2017-04-06
    • 2019-09-08
    • 2020-08-16
    • 2020-02-14
    • 2021-02-25
    相关资源
    最近更新 更多