Postman生成SAS令牌调用Event Grid Topic时授权失败求助
排查Event Grid SAS令牌签名无效问题
以下是导致"Invalid signature"错误的常见原因及修复方案:
1. 资源(resource)格式不符合要求
Event Grid生成SAS令牌时,resource必须是不带HTTP/HTTPS协议、结尾无斜杠的主题端点路径。
- 错误示例:
https://my-topic.westus-2.eventgrid.azure.net/api/events/(带协议+结尾斜杠) - 正确示例:
my-topic.westus-2.eventgrid.azure.net/api/events
检查eventTopicEndpoint集合变量的内容,确保格式正确。
2. 过期时间计算逻辑错误
原脚本中同时混用了毫秒和秒时间戳,导致过期时间异常:
// 错误逻辑:ttl是秒数,却加到了毫秒级的now.getTime()上 var ttl = Math.round(now.getTime() / 1000) + week; var expiration = new Date(); expiration.setTime(now.getTime() + ttl);
修正为统一用秒级时间戳计算:
var now = new Date(); var week = 60*60*24*7; // 7天有效期,单位秒 var expirationTimestamp = Math.round(now.getTime() / 1000) + week; var encodedExpiration = encodeURIComponent(new Date(expirationTimestamp * 1000).toISOString());
3. 签名原始字符串使用了HTML实体转义
原脚本中用&代替了&,导致签名的原始内容与Azure验证要求不符:
// 错误:使用HTML实体& var unsignedSas = `r=${encodedResource}&e=${encodedExpiration}`;
必须改为原始的&:
var unsignedSas = `r=${encodedResource}&e=${encodedExpiration}`;
4. 密钥复制不完整
检查sharedAccessKeyValue集合变量,确保完全复制了Azure门户中Event Grid Topic的访问密钥,没有多余的空格、换行或截断。
修正后的完整预请求脚本
var resource = pm.collectionVariables.get("eventTopicEndpoint"); var key = pm.collectionVariables.get("sharedAccessKeyValue"); var sasToken = createSharedAccessToken(resource, key); pm.collectionVariables.set("sasToken", sasToken); function createSharedAccessToken(resource, key) { if (!resource || !key) { throw "Missing required parameter"; } var now = new Date(); var week = 60*60*24*7; // 7天有效期,单位秒 var expirationTimestamp = Math.round(now.getTime() / 1000) + week; var encodedResource = encodeURIComponent(resource); var encodedExpiration = encodeURIComponent(new Date(expirationTimestamp * 1000).toISOString()); var unsignedSas = `r=${encodedResource}&e=${encodedExpiration}`; var signatureBase64 = CryptoJS.HmacSHA256(unsignedSas, key).toString(CryptoJS.enc.Base64); var encodedSignature = encodeURIComponent(signatureBase64); return `SharedAccessSignature ${unsignedSas}&s=${encodedSignature}`; }
内容的提问来源于stack exchange,提问作者jamesd7198
相关产品推荐
相关产品推荐

