CouchDB 0x00 認(rèn)證
自CouchDB?3.x版本要求訪問數(shù)據(jù)庫時(shí)必須進(jìn)行認(rèn)證。在訪問任何實(shí)際數(shù)據(jù)之前,需向/_session發(fā)送一個(gè)POST請(qǐng)求,要求包括:
(1)Content-Type必須為application/json。
(2)請(qǐng)求體必須為{"name":"xxx",?"password":"yyyy"}
?
如果認(rèn)證成功,這個(gè)請(qǐng)求的響應(yīng)頭部會(huì)包含一個(gè)Set-Cookie域,內(nèi)容大概是:
AuthSession=YWRtaW46NjIxOEQyRDE6tlGcI_YQ_5Dmv3pBsWsjR6W8BSg;?Version=1;?Expires=Fri,?25-Feb-2022?13:10:01?GMT;?Max-Age=600;?Path=/;?HttpOnly
添加一個(gè)新的Cookie。此后的每一個(gè)訪問請(qǐng)求頭部必須帶一個(gè)Cookie域,內(nèi)容就是從AuthSession到第一個(gè)分號(hào)之間的內(nèi)容:
AuthSession=YWRtaW46NjIxOEQyRDE6tlGcI_YQ_5Dmv3pBsWsjR6W8BSg
這個(gè)Cookie是放在頭部的明文,并不安全,應(yīng)當(dāng)添加一個(gè)Apache做SSL代理。瀏覽器一般會(huì)自動(dòng)添加這個(gè)Cookie,但如果是用node.js等環(huán)境,就要考慮手動(dòng)添加了。一段用于驗(yàn)證的實(shí)例代碼如下所示:
const?https?=?require("http");
let?getToken?=?()?=>?{
????return?new?Promise((resolve,?reject)?=>?{
????????var?req?=?https.request("http://localhost:5984/_session",?{
????????????method:?"POST",
????????????headers:?{
????????????????"Content-Type":?"application/json",
????????????}
????????},?(response)?=>?{
????????????if?(!response.headers["set-cookie"])?{
????????????????reject("Authentication?failed.");
????????????}
????????????let?token?=?response.headers["set-cookie"][0];
????????????let?delimaPos?=?token.indexOf(";");
????????????token?=?token.substring(0,?delimaPos);
????????????resolve(token);
????????});
????????req.write(JSON.stringify({
????????????name:?"admin",
????????????password:?"1234546"
????????}));
????????req.end();
????});
};
?
getToken().then((value)?=>?{
????console.log(value);
},?(reason)?=>?{
????console.error(reason);
});