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

问题描述

我正在使用 Microsoft Azure API 管理服务并希望使用 REST API 服务。在创建我的 SAS 令牌时,这是必需的,否则 API 调用不会授权,我很难形成正确的令牌。 Microsoft 的有关此用于 API 管理的 SAS 令牌的网页仅显示了 C# 中的示例。我想知道如何在 Node.js 中形成 SAS 令牌,未显示。下面是我上周运行的代码,但由于某些未知原因现在不起作用。我得到的错误是:401 授权错误,令牌无效

如果有人能帮我制定这个令牌,我将不胜感激。

这是有关此身份验证令牌的 Microsoft 网页:https://docs.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 = '%s\n%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;
};

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)