提取CouchDB以使用Cookie进行身份验证

时间:2020-08-09 20:00:28

标签: cookies fetch couchdb

我正在尝试使用this documentation

进行针对沙发床的身份验证

当我这样做

# 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 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的React应用中工作

Maybe it's CORS related?我在CouchDB设置中启用了CORS。

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

1 个答案:

答案 0 :(得分:-2)

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