鑒權(quán)方式
1 cookie
cookie 是服務(wù)器發(fā)送到用戶瀏覽器并保存在本地的一小塊數(shù)據(jù)耿战,它會(huì)在瀏覽器下次向同一服務(wù)器再發(fā)起請(qǐng)求時(shí)被攜帶并發(fā)送到服務(wù)器上纽乱。
服務(wù)端通過響應(yīng)頭set-cookie將session信息放入瀏覽器cookie
客戶端在請(qǐng)求中將cookie信息放入請(qǐng)求頭
2 jwt (JSON Web Token)
服務(wù)端生成token昆箕, 通過接口等發(fā)送給客戶端
客戶端將token存在本地(如localStorage)鸦列,然后在請(qǐng)求時(shí)通過請(qǐng)求頭帶入
限制
1 cookie HttpOnly
無(wú)法通過js腳本讀寫cookie
2 Chrome 80 版本后的安全策略
Chrome 80.0中將SameSite的默認(rèn)值設(shè)為L(zhǎng)ax,對(duì)現(xiàn)有的Cookie使用有什么影響?
如果 SameSite 值是 Lax, 那么在發(fā)送同站請(qǐng)求的時(shí)候會(huì)帶上 Cookie鹏倘。
3 cookie薯嗤、localStorage纤泵、seesionStorage 等的跨域限制
解決
1 針對(duì)httponly
無(wú)解
2 針對(duì)Chrome Cookie策略
手動(dòng)修改setcookie信息骆姐,samesite設(shè)置為none
3 針對(duì)storage的跨域限制
在工作項(xiàng)目中我使用了利用iframe postMessage傳遞localStorage捏题。
登錄站點(diǎn)
const iframe = document.createElement('iframe');
iframe.src = 'https://xxx.yyy.com';
iframe.style.display='none';
document.body.append(iframe);
// 使用postMessage()方法將token傳遞給iframe
setTimeout(() => {
// eslint-disable-next-line no-console
console.log('posted');
iframe.contentWindow.postMessage(
token,
'https://xxx.yyy.com',
);
}, 4000);
setTimeout(() => {
iframe.remove();
}, 6000);
被傳值站點(diǎn)
window.addEventListener('message', e => {
if (e.source != window.parent) { return; }
console.log(e.data);
localStorage.setItem('task', e.data);
}, false);