我有一个angular 7应用程序,正在使用Couchdb进行身份验证。使用凭证执行POST _session时,将在浏览器中设置cookie。但是,再次执行GET _session以检查身份验证状态时,即使在POST标头中使用withCredentials: true
之后,cookie也不会自动设置。
POST请求:
let _httpHeaders = new HttpHeaders();
_httpHeaders = _httpHeaders.set('Accept', 'application/json');
_httpHeaders = _httpHeaders.set('Content-type', 'application/json');
_httpHeaders = _httpHeaders.set('Authorization', 'Basic ' + btoa(data.name + ':' + data.password));
const options = { headers: _httpHeaders, withCredentials: true };
console.log(options);
return this._httpService.doAsyncTask(AppConstants.LOGIN_URL, 'POST', data, options);
GET请求:
return this._httpService.doAsyncTask(AppConstants.LOGIN_URL + '?basic=true', 'GET');
在GET请求的标头中设置withCredentials: true
也不起作用。
我得到的答复:
{“错误”:“未经授权”,“原因”:“请登录。”}
GET调用的请求和响应头: 请求标头:
Accept: application/json, text/plain, */*
Origin: http://localhost:5800
Referer: http://localhost:5800/login
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
响应标题:
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: 50
Content-Type: application/json
Date: Fri, 14 Jun 2019 09:41:31 GMT
Server: nginx/1.10.3 (Ubuntu)
X-Couch-Request-ID: 3fb687405b
X-CouchDB-Body-Time: 0
答案 0 :(得分:0)
我解决了。 withCredentials: true
标头需要设置为GET请求。正确的发送方式是:
let _httpHeaders = new HttpHeaders();
_httpHeaders = _httpHeaders.set('Accept', 'application/json');
_httpHeaders = _httpHeaders.set('Content-type', 'application/json');
const options = { headers: _httpHeaders, withCredentials: true };
return this._httpService.doAsyncTask(AppConstants.LOGIN_URL + '?basic=true', 'GET', '', options);
作为响应,您将获得userCtx对象。
{"ok":true,"userCtx":{"name":"username","roles":["sales"]},"info":{"authentication_db":"_users","authentication_handlers":["cookie","default"],"authenticated":"cookie"}}
我希望这可以帮助遇到相同问题的人。