1. window.postMessage 在 iframe 跨源通信的 origin 校验工程风险与最佳实践
请说明 window.postMessage 在 iframe 跨源通信中的 origin 校验工程风险与最佳实践?
- postMessage 的 targetOrigin 与 event.origin
- 未校验 origin 的消息注入风险
- 最佳实践(校验 origin、白名单、数据序列化)
postMessage 允许跨源窗口通信,但存在安全风险:若不校验 event.origin,恶意页面可通过 iframe 注入任意消息,导致安全漏洞。最佳实践:1) 发送时指定 targetOrigin(应为具体源而非 *);2) 接收时校验 event.origin 是否在信任白名单内;3) 对消息内容做类型/结构校验(防 prototype pollution);4) 使用 JSON 序列化安全的 payload。支付、登录等敏感操作不能仅依赖 postMessage 的 origin 校验,需配合其他校验。工程风险:遗漏 origin 校验、使用 *、信任任意消息源。
postMessage 的信任模型是"显式校验 origin"。原理是 event.origin 提供发送者来源,但必须自己比对白名单。这是 iframe 跨源通信安全的基础。
window.addEventListener('message', (e) => {
if (e.origin !== 'https://trusted.example.com') return; // 校验 origin
const data = typeof e.data === 'string' ? JSON.parse(e.data) : e.data;
// 处理
});