如何在 Node.js 中为 Azure API Management 的 REST API Microsoft形成 SAS 令牌?



我正在使用微软Azure API管理服务,并希望使用REST API服务。在创建SAS令牌时(这是必需的,否则API调用不会授权),我在形成适当的令牌时遇到了困难。微软关于API管理的SAS令牌的网页只展示了一个c#的例子。我想知道如何在Node.js中形成SAS令牌,这没有显示。下面是我的代码,上周工作,但现在不知道的原因。我得到的错误是:401授权错误,令牌无效

如果有人能帮我制定这个令牌,我会很感激的。

这是微软关于这个身份验证令牌的网页:https://learn.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/azure-api-management-rest-api-authentication

下面是我的代码:

const crypto = require('crypto');
const util = require('util');
const sign = () => {
const id = ${process.env.id}
const key = `${process.env.SASKey}`;
const date = new Date();
const newDate = new Date(date.setTime(date.getTime() + 8 * 86400000));
const expiry = `${newDate.getFullYear()}${
newDate.getMonth() < 10
? '' + newDate.getMonth() + 1
: newDate.getMonth() + 1
}${newDate.getDate()}${newDate.getHours()}${
newDate.getMinutes() < 10
? '0' + newDate.getMinutes()
: newDate.getMinutes()
}`;
const dataToSignString = '%sn%s';
const dataToSign = util.format(dataToSignString, ${id}, expiry);
const hash = crypto
.createHmac('sha512', key)
.update(dataToSign)
.digest('base64');
const encodedToken = `SharedAccessSignature ${id}&${expiry}&${hash}`;
console.log(encodedToken);
return encodedToken;
};

试试代码:

protected getAPIManagementSAS(){
let utf8 = require("utf8")
let crypto= require("crypto")
let identifier = process.env.API_IDENTIFIER;
let key = process.env.API_KEY;
var now = new Date;
var utcDate = new Date(now.getUTCFullYear(),now.getUTCMonth(), now.getUTCDate() , now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
let expiry = addMinutes(utcDate,1,"yyyy-MM-ddThh:mm:ss") + '.0000000Z'
var dataToSign = identifier + "n" + expiry;
var signatureUTF8 = utf8.encode(key); 
var signature = crypto.createHmac('sha512', signatureUTF8).update(dataToSign).digest('base64'); 
var encodedToken = `SharedAccessSignature uid=${identifier}&ex=${expiry}&sn=${signature}`;   
return encodedToken
}

更多信息请参见此处

在尝试了一百万次之后,似乎现在唯一可以接受的格式是:SharedAccessSignature uid=${identifier}&ex=${expiry}&sn=${signature}

如果您正在使用具有"集成"的其他格式参数,这是命中或未命中,但主要是未命中。将uid设置为"integration";如果这是你的标识符,请按照上面的格式操作。

最新更新