2018-11-06更新:
如果在chrome瀏覽器中過(guò)期時(shí)間 expiration date顯示的是1969。
答案
說(shuō)明cookie是臨時(shí)的,只保持在這個(gè)會(huì)話周期,當(dāng)瀏覽器關(guān)閉時(shí)cookie會(huì)被清除。
Unix time was started at the beginning of 1970, that means that -1 is in 1969. And that is a commonly used value for "unknown" if the expected value is usually positive. And for cookies MaxAge with a negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits.
2018-08-27更新:
使用cookie前強(qiáng)烈建議先看下MDN的這篇基礎(chǔ)文章
創(chuàng)建cookie可以配置的選項(xiàng) Expires,Secure,HttpOnly,Domain,Path,SameSite。
為避免跨域腳本 (XSS) 攻擊,通過(guò)JavaScript的 Document.cookie API無(wú)法訪問(wèn)帶有 HttpOnly 標(biāo)記的Cookie,它們只應(yīng)該發(fā)送給服務(wù)端。
最近在開(kāi)發(fā)一個(gè)前后臺(tái)分離的項(xiàng)目。
前臺(tái)是 localhost:8080,基于vue,請(qǐng)求用的axios庫(kù),后臺(tái)是地址 localhost:8111,使用的是NodeJS。
也就是前臺(tái)發(fā)起的請(qǐng)求是跨域的。
現(xiàn)在流程是這樣的: 前臺(tái)向后臺(tái)請(qǐng)求接口,后臺(tái)會(huì)看到set-cookie,可是我發(fā)現(xiàn)前端JS 怎么也拿不到 cookie(后來(lái)發(fā)現(xiàn)是cookie被設(shè)置了HttpOnly)。axios的response里沒(méi)有。但是在chrome里可以看到設(shè)置的cookie。
查了文檔,當(dāng)需要跨域請(qǐng)求,前臺(tái)需要設(shè)置 withCredentials 為 true。 這樣每次請(qǐng)求會(huì)自動(dòng)帶上 cookie,但是后臺(tái)也需要設(shè)置 Access-Control-Allow-Credentials: true, 就不能用*來(lái)設(shè)置Origin了,即 Access-Control-Allow-Origin:* , 而應(yīng)該相應(yīng)的改成Access-Control-Allow-Origin: localhost:8080,
這樣就比較尷尬了,到時(shí)候前臺(tái)是對(duì)大眾開(kāi)放,需要允許所有來(lái)源,難道沒(méi)有別的辦法了?相信標(biāo)準(zhǔn)這么做也是為了安全。
查了也有解決辦法。都還沒(méi)有嘗試。
比如
- 可以在nginx中設(shè)置,對(duì)于過(guò)來(lái)的請(qǐng)求,讓 nginx 自動(dòng)加上請(qǐng)求頭。下面的方法沒(méi)試,不是嫌麻煩,是部署的工作不是自己的人來(lái)做。
if ($http_origin ~* ( https?://.*\.example\.com(:[0-9]+)?$)) {
add_header Access-Control-Allow-Origin: $http_origin;
}
- 對(duì)于后端,比如express。每個(gè)請(qǐng)求都走一遍中間件, 取出 headers 里的域名, 寫到 CORS 頭部去:
app = express()
app.all('/*', (req, res, next) => {
if (req.headers.origin) {
res.header("Access-Control-Allow-Origin", req.headers.origin)
res.header("Access-Control-Allow-Credentials", true)
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS')
# 下面一行意義不明確...
res.header("Access-Control-Allow-Headers", "X-Requested-With, AUTHORIZATION")
}
next(); // pass control to the next handler
});
next()
其實(shí)使用cookie做前后端分離真的沒(méi)有 token 或 jwt 好用。機(jī)密的信息不要放到cookie中比較好。
====
更新
使用下面的方法在本地可行
if (process.env.NODE_ENV == 'local') {
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
}else {
app.use(cors());
}