【问题标题】:Connect to Azure Blob Storage REST API with axios, Node.js使用 axios、Node.js 连接到 Azure Blob 存储 REST API
【发布时间】:2020-11-30 10:00:08
【问题描述】:

我正在尝试使用 Node.js 连接到 Azure blob 存储 API。我特别不想使用 Blob 存储 SDK,我想使用 axios 来打 REST API。我只是想按照此处指定的方式进行简单的列表容器调用:https://docs.microsoft.com/en-us/rest/api/storageservices/list-containers2。但是,我遇到了授权问题。

这是我的简单 axios 调用:

try {
  const azureRes = await axios({
    method: 'GET',
    url:
      'https://<accountname>.blob.core.windows.net/?comp=list',
    headers: {
      'x-ms-version': '2017-11-09',
      Authorization:
        'Bearer <access_token>'
    }
  });
  console.log('azureRes', azureRes);
} catch (err) {
  console.log('err:', err);
}

但是我收到了带有 403 状态代码和错误消息的响应:

Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

我正在根据https://docs.microsoft.com/en-us/rest/api/storageservices/authorize-with-azure-active-directory 进行身份验证,并且我正在从 Azure 存储帐户访问密钥选项卡获取我的访问令牌。为什么我的身份验证失败?

【问题讨论】:

  • 能否详细说明您是如何获得访问令牌的?
  • 从“密钥”下的 Azure 存储帐户“访问密钥”选项卡中
  • 嗨。它是访问密钥而不是 AD 访问令牌。如果你想通过 AD auth 访问存储,请参考我的解决方案。

标签: node.js reactjs azure axios azure-blob-storage


【解决方案1】:

如果你想通过 Azure AD auth 访问 Azure blob REST API,请参考以下步骤

  1. Storage Blob Data Contributor 分配给AD 用户或服务主体。更多详情请参考herehere
az role assignment create \
    --role "Storage Blob Data Contributor" \
    --assignee " supported format: object id, user sign-in name, or service principal name." \
    --scope "/subscriptions/<subscription>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>"
  1. 获取 Azure AD 令牌

如果您使用服务主体,我们可以通过以下 API 获取访问令牌。但请注意,如果您在 React 应用程序中调用其余 API,则会出现 cors 错误,我们无法在 Azure AD 上启用 cors。所以我建议你在后端应用程序中调用其余的 API

POST /{tenant}/oauth2/v2.0/token HTTP/1.1          
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded

client_id=
&scope=http//storage.azure.com/.default
&client_secret=
&grant_type=client_credentials

如果您使用 Azure AD 用户,您可以将 Azure AD 身份验证与包 react-aad-msal 集成到您的 React 应用程序中。关于如何配置,请参考sample

  1. 调用 API
try {
  const azureRes = await axios({
    method: 'GET',
    url:
      'https://<accountname>.blob.core.windows.net/?comp=list',
    headers: {
      'x-ms-version': '2017-11-09',
      Authorization:
        'Bearer <access_token>'
    }
  });
  console.log('azureRes', azureRes);
} catch (err) {
  console.log('err:', err);
}

更新 关于如何创建sas token,请参考以下代码

  1. 安装 pcakge crypto-js
npm install crypto-js

  1. 代码
import * as CryptoJS from 'crypto-js';
const accountName =<>;
  const key=<>;
  const start = new Date(new Date().getTime() - (15 * 60 * 1000));
  const end = new Date(new Date().getTime() + (30 * 60 * 1000));
const signedpermissions = 'rwdlac';
  const signedservice = 'b';
  const signedresourcetype = 'sco';
  const signedexpiry = end.toISOString().substring(0, end.toISOString().lastIndexOf('.')) + 'Z';
  const signedProtocol = 'https';
  const signedversion = '2018-03-28';

  const StringToSign =
      accountName+ '\n' +
      signedpermissions + '\n' +
      signedservice + '\n' +
      signedresourcetype + '\n' +
       '\n' +
      signedexpiry + '\n' +
       '\n' +
      signedProtocol + '\n' +
signedversion + '\n';

 var str =CryptoJS.HmacSHA256(StringToSign,CryptoJS.enc.Base64.parse(key));
 var sig = CryptoJS.enc.Base64.stringify(str);
 
 
  const sasToken =`sv=${(signedversion)}&ss=${(signedservice)}&srt=${(signedresourcetype)}&sp=${(signedpermissions)}&se=${encodeURIComponent(signedexpiry)}&spr=${(signedProtocol)}&sig=${encodeURIComponent(sig)}`;

const blobUrl= `<you blob URL>?{sasToken }`

【讨论】:

猜你喜欢
  • 2022-08-03
  • 2019-11-08
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 2020-05-28
  • 1970-01-01
  • 2015-05-29
  • 2021-07-11
相关资源
最近更新 更多