Express 授權中介軟體:檢查使用者與資源
授權中介軟體在伺服器端判斷已確認身分的使用者能否對特定資源執行操作。本文以 Express 5 文件 API 說明物件層級權限、預設拒絕、回應與路由順序。程式碼僅供說明,未執行。
授權中介軟體在伺服器端判斷已確認身分的使用者能否對特定資源執行操作。本文以 Express 5 文件 API 說明物件層級權限、預設拒絕、回應與路由順序。程式碼僅供說明,未執行。
驗證與授權
驗證確認請求代表誰;授權判斷該主體能否對指定資源執行操作。登入成功或持有有效權杖不代表可存取所有文件。每個非公開 API 端點都需檢查存取權。 (OWASP Authorization)
Express 中介軟體允許時呼叫 next;拒絕時結束回應,不執行受保護操作。資料儲存或政策服務的意外錯誤應進入錯誤處理流程,不應偽裝成一般拒絕。 (Express middleware)
為何只檢查角色不夠?
RBAC 將權限連結到角色,但同角色使用者不一定能讀取彼此文件。判斷可依主體、資源、關係、租戶、狀態及操作而定。每個請求與物件都要檢查,並預設拒絕。 (OWASP Authorization)
A 能讀自己的文件,不代表把 URL ID 換成 B 的文件即可通過。難猜的 UUID 不能取代授權。清單、搜尋與匯出也要限制範圍。 (OWASP IDOR Prevention)
在 Express 5 檢查文件權限
範例假設前一步已把確認過的使用者 ID 放入 req.principal。中介軟體載入文件,將主體、操作和資源交給政策。所有權與租戶規則依應用程式實作。
import type { RequestHandler } from 'express';
type Principal = { subject: string };
type Document = { id: string; ownerId: string; tenantId: string };
type Action = 'read' | 'edit';
declare global {
namespace Express {
interface Request {
principal?: Principal;
document?: Document;
}
}
}
interface DocumentStore {
findById(id: string): Promise<Document | null>;
}
interface DocumentPolicy {
allows(input: {
subject: Principal;
action: Action;
resource: Document;
}): Promise<boolean>;
}
export function requireDocumentPermission(
action: Action,
store: DocumentStore,
policy: DocumentPolicy,
): RequestHandler {
return async (req, res, next) => {
if (!req.principal) {
res.sendStatus(401);
return;
}
try {
const document = await store.findById(req.params.documentId);
if (!document) {
res.sendStatus(404);
return;
}
const allowed = await policy.allows({
subject: req.principal,
action,
resource: document,
});
if (!allowed) {
res.sendStatus(403);
return;
}
req.document = document;
next();
} catch (error) {
next(error);
}
};
}政策必須明確允許;缺少規則、錯誤或輸入不完整都不代表允許。文件不存在時回傳 404 是 API 選擇。若要隱藏資源是否存在,可依一致契約對無權限請求也回相同結果。資料或政策服務故障應進入伺服器錯誤處理,而非 403。 (OWASP Authorization)
路由順序
依序執行驗證、文件授權、受保護處理常式。Express 按註冊順序執行;漏掉檢查的 URL/方法組合可能形成繞過路徑。也要檢查下載與管理操作。 (Express using middleware)
router.patch(
'/documents/:documentId',
requireAuthentication(tokenVerifier),
requireDocumentPermission('edit', documentStore, documentPolicy),
async (req, res) => {
const updated = await documentService.update(req.document!, req.body);
res.json(updated);
},
);清單與搜尋
將查詢限制在使用者可存取的租戶、專案和文件,不要先取回全部資料再隱藏結果。筆數、匯出與靜態檔案也納入權限範圍。角色不代表物件所有權,瀏覽器隱藏按鈕也不會保護伺服器。 (OWASP Authorization)
檢查拒絕情況
通常未驗證回 401,已驗證但無權限回 403;一致的 404 可隱藏資源存在與否。
不要信任未驗證請求本文或標頭中的 ownerId、tenantId、role。
不揭露內部政策或錯誤堆疊,也不記錄機密。
用 A、B 使用者檢查讀取、修改、刪除、清單、搜尋、匯出及替代路徑。範例未在應用程式執行。