這是我的后端代碼。它有 2 條受保護的路線。需要授權標頭(承載令牌)。
- 這些路線允許您下載照片和簡歷。
我的后端沒有問題。它與郵遞員和移動應用程式一起使用。我認為前端有一個限制。
我不想
- 我不想使用 fetch 將這些檔案下載為 blob。因為它不允許瀏覽器顯示其進度條。
- 我不想將身份驗證方法從 Bearer 令牌更改為 cookie。我已經可以用 cookie 做到這一點。
如果我必須使用 cookie 來實作這一點,我想知道為什么 Bearer 令牌比 cookie 更受歡迎。
后端
// other imports .....
const path = require('path');
const fs = require('fs');
const express = require('express');
const app = express();
app.use((req, res, next) => {
try {
const token = req.get('Authorization');
if(!token) {
throw new Error('401');
}
const userId = getIdFromToken(token);
if(!userId) {
throw new Error('401');
}
res.locals.userId = userId;
next();
} catch (error) {
next(error);
}
})
app.get('/api/me/photo', (req, res) => {
const userId = res.locals.userId;
const imagePath = path.resolve(process.env.DISC_PATH, 'images', `${userId}.png`);
res.attachment('me.png');
res.set('Content-Type', 'image/png');
const stream = fs.createReadStream(imagePath);
res.pipe(stream);
})
app.get('/api/me/cv', (req, res) => {
const userId = res.locals.userId;
const pdfPath = path.resolve(process.env.DISC_PATH, 'cv', `${userId}.png`);
res.attachment('my-cv.pdf');
res.set('Content-Type', 'application/pdf');
const stream = fs.createReadStream(pdfPath);
res.pipe(stream);
})
...
// error handling, etc...
前端
<html>
<body>
<!-- How can I send the Authorization header here -->
<img src="/api/me/photo" />
<!-- How can I send the Authorization header here -->
<a href="/api/me/cv">Download My CV</a>
<!-- How can I send the Authorization header here -->
<button id="btn"> Download My CV (V2) </button>
<script>
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
// How can I send the Authorization header here
window.open('/api/me/cv');
});
</script>
</body>
</html>
uj5u.com熱心網友回復:
如果我必須使用 cookie 來實作這一點,我想知道為什么 Bearer 令牌比 cookie 更受歡迎。
與基于 cookie 的身份驗證相比,標頭的一個優點Authorization: Bearer正是瀏覽器不會自動將標頭包含在對給定 URL 的請求中。因此,您不會被誘騙點擊會觸發您不希望的經過身份驗證的請求的鏈接。
換句話說:使用Authorization: Bearer身份驗證機制,您可以免受“跨站點請求偽造”(CSRF)攻擊。
使用基于 cookie 的身份驗證的后端必須針對 CSRF 實施額外的對策。
對于您的問題,這意味著兩者不會在一起。如果您想要“正常”瀏覽器請求(帶有進度條)的便利,則將用戶暴露給 CSRF,除非您采取上述對策。(如果請求只下載一些東西,這可能不是一個嚴重的威脅。但攻擊者至少可以測量 CV 下載請求的運行時間并從中推斷出一些東西。)
可能的解決方法:
實作一個 API(使用Authorization: Bearer標頭進行身份驗證),該 API 生成一個包含短期令牌的下載 URL,并讓瀏覽器通過對該 URL 的正常請求下載所需的檔案。第二個請求在技術上未經身份驗證,但令牌使 URL 不可猜測。
如果令牌是 JWT,您甚至不需要將其存盤在服務器上,只需在其中寫入用戶名和到期時間,并使用服務器的私鑰對其進行簽名。如果您愿意,也可以將令牌放在 cookie 中而不是 URL 中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489770.html
