cors与自定义签名头协同防刷:cors控制跨域预检放行,签名头(x-signature/x-timestamp/x-nonce)由服务端校验合法性、防重放与伪造,二者分工明确、缺一不可。

用 CORS 配合自定义签名头防刷,核心不是靠 CORS 本身做鉴权,而是利用 CORS 的预检机制 + 服务端签名验证形成双重拦截:浏览器先走 OPTIONS 预检(被 CORS 规则控制),再发带签名的真实请求(由后端业务逻辑校验)。CORS 负责“放行合法跨域行为”,签名头负责“识别真实合法调用者”。两者配合才能兼顾兼容性与安全性。
明确 CORS 和签名头的分工
CORS 是浏览器强制执行的协商机制,只管“能不能发请求”,不管“请求内容是否可信”;自定义签名头(如 X-Signature、X-Timestamp、X-Nonce)才是服务端验证请求合法性、防重放、防伪造的关键。必须分开设计:
- CORS 配置要允许该签名头出现在请求中(通过 Access-Control-Allow-Headers 显式声明)
- 服务端中间件必须在业务逻辑前解析并校验签名,失败则直接返回 401/403,不进路由
- 不能依赖前端 JS 生成“不可破解”的签名——密钥必须只存在于服务端,前端只能参与可公开的参数拼接(如时间戳+随机数+请求路径)
服务端配置:让签名头合法跨域
以 Express + cors 中间件为例,需确保预检请求能通过,并允许携带签名相关字段:
const corsOptions = {
origin: ['https://your-trusted-fe.com', 'https://admin.yourapp.com'],
credentials: true,
allowedHeaders: [
'Content-Type',
'Authorization',
'X-Signature', // ← 必须显式列出
'X-Timestamp',
'X-Nonce'
],
methods: ['GET', 'POST', 'PUT', 'DELETE'],
optionsSuccessStatus: 204
};
<p>app.use(cors(corsOptions));
// 或更细粒度:只对 /api/** 启用
app.use('/api', cors(corsOptions));
</p>
⚠️ 注意:origin 不能写 *,否则 Access-Control-Allow-Credentials: true 会失效,导致 Cookie 和 Authorization 头无法发送——而签名验证往往依赖用户登录态或 session。
签名验证逻辑(服务端关键步骤)
收到带签名头的请求后,服务端需按约定规则还原签名并比对。典型流程:
将一个或多个视频上传至YouTube。当用户想“上传到YouTube”“发YouTube”“批量上传”“upload to YouTube”“post videos to YouTube”或发布到YouTube时使用此技能。
- 提取 X-Timestamp,拒绝超过 300 秒的请求(防重放)
- 检查 X-Nonce 是否已存在缓存(Redis 最佳),避免同一随机数重复使用
- 按固定顺序拼接待签名字符串:HTTP 方法 + 请求路径 + X-Timestamp + X-Nonce + 请求体摘要(如 SHA256(body) 截取前16位)
- 用服务端持有的密钥(如 process.env.API_SECRET)对该字符串做 HMAC-SHA256,Base64 编码
- 比对结果与 X-Signature 是否一致
示例验证中间件(Express):
const crypto = require('crypto');
const redis = require('redis'); // 或其他存储
<p>app.use('/api', async (req, res, next) => {
const timestamp = req.headers['x-timestamp'];
const nonce = req.headers['x-nonce'];
const signature = req.headers['x-signature'];</p><p>if (!timestamp || !nonce || !signature) {
return res.status(400).json({ error: 'Missing required headers' });
}</p><p>if (Date.now() - parseInt(timestamp) > 300000) {
return res.status(401).json({ error: 'Request expired' });
}</p><p>const exists = await redis.get(<code>nonce:${nonce}</code>);
if (exists) {
return res.status(401).json({ error: 'Nonce reused' });
}
await redis.setex(<code>nonce:${nonce}</code>, 300, '1'); // 5分钟有效期</p><p>const bodyHash = req.method === 'GET' ? '' :
crypto.createHash('sha256').update(JSON.stringify(req.body)).digest('base64').substring(0, 16);</p><p>const signStr = [req.method, req.path, timestamp, nonce, bodyHash].join('|');
const expected = crypto
.createHmac('sha256', process.env.API_SECRET)
.update(signStr)
.digest('base64');</p><p>if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
return res.status(401).json({ error: 'Invalid signature' });
}</p><p>next();
});
</p>
前端调用时的注意事项
前端 JS 发起请求时,需同步生成签名并设置对应 header:
- 时间戳用 Date.now(),和服务端比对时注意时区无关(都是毫秒时间戳)
- 随机数 nonce 建议用 crypto.randomUUID() 或安全随机字符串(避免 Math.random)
- 签名计算必须和服务端完全一致(大小写、分隔符、空格、body 序列化方式)
- fetch 请求需显式开启 credentials: 'include' 才能携带 Cookie,且后端 credentials: true 必须匹配
简单 fetch 示例:
const timestamp = Date.now().toString();
const nonce = crypto.randomUUID();
const body = JSON.stringify({ id: 123 });
const bodyHash = btoa(crypto.subtle.digest('SHA-256', new TextEncoder().encode(body)).slice(0, 8));
<p>const signStr = <code>POST|/api/user/update|${timestamp}|${nonce}|${bodyHash}</code>;
const signature = btoa(await crypto.subtle.importKey('raw', new TextEncoder().encode(API_SECRET), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
.then(key => crypto.subtle.sign('HMAC', key, new TextEncoder().encode(signStr))));</p><p>fetch('/api/user/update', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Signature': signature,
'X-Timestamp': timestamp,
'X-Nonce': nonce
},
body,
credentials: 'include'
});
</p>
⚠️ 实际项目中,签名逻辑建议封装为 SDK,避免各端重复实现出错。










