首页 > 解决方案 > 获取 CouchDB 以使用 cookie 进行身份验证

问题描述

我正在尝试使用此文档对 couchdb 进行身份验证

当我做

# first request
const url = 'http://localhost:5984/_session'
fetch(url, {
    method: 'POST',
    headers: {
        "Content-Type": "application/json",
    },
    body : JSON.stringify({
        "name": "my_username",
        "password": "my_password"
    }),
}).then( data => {
    console.log(data)
}).catch(e => {
    console.log('Error', e)
})

如果 my_username 或 my_password 之一不正确,我会得到:

body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 401
statusText: "Unauthorized"
type: "cors"
url: "http://localhost:5984/_session"

这很好。

但是,如果 my_username 或 my_password 之一是正确的,我会得到:

body: ReadableStream
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
url: "http://localhost:5984/_session"

代替

HTTP/1.1 200 OK
Cache-Control: must-revalidate
Content-Length: 43
Content-Type: application/json
Date: Mon, 03 Dec 2012 01:23:14 GMT
Server: CouchDB (Erlang/OTP)
Set-Cookie: AuthSession=cm9vdDo1MEJCRkYwMjq0LO0ylOIwShrgt8y-UkhI-c6BGw; Version=1; Path=/; 
HttpOnly

{"ok":true,"name":"root","roles":["_admin"]}  // <-- i expect that

并且没有设置 cookie。

我也试过 curl,它有效:

> curl http://localhost:5984/_session
{"ok":true,"userCtx":{"name":null,"roles":[]},"info":{"authentication_handlers": 
["cookie","default"]}}

> curl -X POST http://localhost:5984/_session -H "Content-Type: application/json" -d '{"name":"my_username","password":"my_password"}'
{"ok":true,"name":"my_username","roles":["_admin"]}

但我需要它在反应应用程序中工作,来自 http:localhost:3000

也许它与CORS有关?我在 CouchDB 设置中启用了 CORS。

如何修改第一个请求以获取提供的名称/密码的用户对象?

标签: cookiesfetchcouchdb

解决方案


我认为 Authentication Set-Cookie 由后端服务器而不是前端产生。所以你需要像 Node.js 这样的后端来获取 cookie,然后从你的前端再次获取它。


推荐阅读