【发布时间】:2018-10-11 00:41:02
【问题描述】:
环境:
CouchDB 2.2.0 在 VirtualBox 上运行,运行最新的 Debian 映像。网络类型是桥接的,所有端口都是开放的,没有https。
Vue3.js 应用(不使用任何 Vue 功能访问数据库)
-
远程访问JS包:
- axios
- 获取
浏览器:Chrome 最新版
相关的 CouchDB local.ini 设置
[couch_peruser]
enable = false
delete_dbs = false
[chttpd]
port = 5984
require_valid_user = false
proxy_use_secret = false
bind_address = 0.0.0.0
authentication_handlers = {chttpd_auth, cookie_authentication_handler}, {chttpd_auth, default_authentication_handler}
[httpd]
bind_address = 127.0.0.1
enable_cors = true
(default authentication handlers set in default.ini)
authentication_handlers = {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, default_authentication_handler}
[couch_httpd_auth]
secret = (hash num)
require_valid_user = false
allow_persistent_cookies = true
[cors]
origins = *
headers = accept, authorization, content-type, X-Auth-CouchDB-UserName, origin, referer
credentials = true
methods = GET, PUT, POST, HEAD, DELETE
会发生什么
如果我通过 curl 进行查询,我会在响应中得到一个 cookie。
这是 curl 调用:
curl -v http://couchman.lcldev:5984/_session \
-H "Content-Type:application/json" \
-H "X-Auth-CouchDB-UserName:<uname>" \
-d '{"name":"<uname>","password":"<passwd>"}'
下面是回复:
< HTTP/1.1 200 OK
< Cache-Control: must-revalidate
< Content-Length: 47
< Content-Type: application/json
< Date: Wed, 10 Oct 2018 21:16:10 GMT
< Server: CouchDB/2.2.0 (Erlang OTP/19)
< Set-Cookie: (cookie info)
<
{"ok":true,"name":"<name>","roles":["<roles>"]}
是的。我得到一个饼干。
但如果我从我的应用程序中调用它(使用 fetch 或 axios),我只会得到这些标题:
Response headers:
cache-control,must-revalidate
content-type,application/json
server,CouchDB/2.2.0 (Erlang OTP/19)
没有 Set-Cookie 标头。
那么,怎么了?我错过了什么?
【问题讨论】:
-
确保在前端 JavaScript 代码中为请求设置了 'withCredentials: true' 或 'credentials:"include"'。
-
您好,感谢您的回复。因此,在“获取”中,我设置了“凭据”:“包含”,它确实在浏览器中设置了一个 cookie,我可以在“应用程序”调试输出中看到。但是,我没有看到标题。浏览器会吸收吗?下一个问题是如何获得它,以便在后续请求中将其传递给 CB?我没有得到标题,并且“document.cookie”没有显示任何内容。 (在 axios 中设置 'withCredentials: true' 没有产生 cookie,顺便说一句)
-
(该应用程序是 PWA,顺便说一句。我认为这不会有什么不同,但我想知道 PWA 中 cookie 的处理方式是否不同?必须研究......)
-
浏览器永远不会让您从前端 JavaScript 代码访问 Set-Cookie 响应标头。 Set-Cookie 被定义为“禁止的”响应头名称。见fetch.spec.whatwg.org/#forbidden-response-header-name。在这种情况下,“禁止”意味着禁止前端代码访问具有该名称的任何响应标头。 Set-Cookie 仅供浏览器本身使用。
-
明白了。所以,我(认为)我仍然必须让它呈现给 CB 以供后续查询。经过研究,似乎 google.chrome 已经实现了一种全新的访问 cookie 的机制,它可能与 PWA/ServiceWorker imp 有关。必须学习更多...
标签: google-chrome authentication couchdb session-cookies progressive-web-apps