跳至主要內容

保護 Webhook

當你的伺服器準備好接收 Webhook 請求後,你可能希望確保它能安全地處理這些請求。Logto 為每個 Webhook 請求的有效負載生成一個簽名,這使你能夠驗證請求是否來自 Logto。

獲取簽名金鑰

你需要從 Logto Console > Webhooks 的 Webhook 詳細資訊頁面獲取簽名金鑰,以驗證簽名。

驗證簽名

從 Webhook 請求的 logto-signature-sha-256 標頭中提取簽名。

之後,你應該使用你的簽名金鑰和 Webhook 請求的主體生成一個簽名,並確保結果與來自 Logto 的簽名匹配。

備註:

使用 Webhook 請求的原始主體來生成簽名;避免使用已解析的主體,因為伺服器可能會在到達你的 Webhook 端點處理器之前對其進行預處理。

Logto 使用 HMAC 十六進位摘要來計算簽名。

以下是在 Node.js 中驗證簽名的範例:

import { createHmac } from 'node:crypto';

export const verify = (signingKey: string, rawBody: Buffer[], expectedSignature: string) => {
const hmac = createHmac('sha256', signingKey);
hmac.update(rawBody);
const signature = hmac.digest('hex');
return signature === expectedSignature;
};