【问题标题】:Using Bearer tokens along with azure-sdk-for-js将 Bearer 令牌与 azure-sdk-for-js 一起使用
【发布时间】:2023-03-04 03:59:01
【问题描述】:

我们正在构建一个 nodejs 服务器,它使用 AAD 对用户进行身份验证。当用户登录我们的应用程序时,我们会从 Microsoft 登录端点获得 JWT accessToken

我们如何使用这个令牌来调用使用这个 javascript API 来获取 blob/containers?我不想使用 (Authorization: Bearer accessToken) 调用直接向 API 发出 ajax 请求。

我已经成功使用这样的邮递员拨打电话了?如何使用 blobServiceClient 以编程方式执行此操作?

【问题讨论】:

  • Cloud 你告诉我你用的是哪个 azure storage sdk?
  • 嗨,我使用@azure/storage-blob
  • 根据我的研究,如果我们使用V10版本的SDK@azure/storage-blob我们可以直接使用Azure AD访问令牌来管理azure blob服务。因为sdk提供了TokenCredential类。我们可以使用代码const tokenCredential = new azure.TokenCredential("token") 来初始化一个凭证,然后使用它来获取 blob。更多详情请参考npmjs.com/package/@azure/storage-blob/v/10.5.0docs.microsoft.com/en-us/azure/storage/blobs/…
  • 我现在将此库与 TokenCredential 一起使用。每当我尝试下载 blob 时,都会收到 403 响应。但是如果我使用 sharedkeycredentials 那么 blob 下载就可以了。可能是什么问题?
  • 既然您的问题已经解决了,请问您能接受吗?它可能会帮助更多有类似问题的人。

标签: azure azure-active-directory azure-storage azure-blob-storage azure-container-service


【解决方案1】:

根据我的研究,如果我们使用 V10 版本的 SDK @azure/storage-blob 我们可以直接使用 Azure AD 访问令牌来管理 azure blob 服务。因为sdk提供类TokenCredential。我们可以使用代码const tokenCredential = new azure.TokenCredential("token")来初始化一个凭证,然后用它来获取blob。

例如

const azure = require("@azure/storage-blob"); 

async function getBlobContent(){

    const tokenCredential = new azure.TokenCredential("")
    const pipeline =  azure.StorageURL.newPipeline(tokenCredential)
    const serviceURL = new azure.ServiceURL(`https://jimtestperfdiag516.blob.core.windows.net`, pipeline);
    const containerURL = azure.ContainerURL.fromServiceURL(serviceURL, "test");
    const blockBlobURL = azure.BlockBlobURL.fromContainerURL(containerURL, "test.csv");
    const aborter=azure.Aborter.timeout(30* 60 * 1000)
    const downloadResponse = await blockBlobURL.download(aborter, 0);
    const downloadedContent = await streamToString(downloadResponse.readableStreamBody);
    console.log(`Downloaded blob content: "${downloadedContent}"`);



}

async function streamToString(readableStream) {
    return new Promise((resolve, reject) => {
      const chunks = [];
      readableStream.on("data", data => {
        chunks.push(data.toString());
      });
      readableStream.on("end", () => {
        resolve(chunks.join(""));
      });
      readableStream.on("error", reject);
    });
}

getBlobContent()
  .then(() => {
    console.log("Successfully executed sample.");
  })
  .catch((err) => {
    console.log(err.message);
  });

更多详情请参考https://www.npmjs.com/package/@azure/storage-blob/v/10.5.0https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-nodejs-legacy

此外,请注意,如果您想使用 Azure AD 访问 azure blob,我们需要将 RABS 角色(Storage Blob Data Owner Storage Blob Data Contributor 或 Storage Blob Data Reader)分配给用户或服务主体:https://docs.microsoft.com/en-us/azure/storage/common/storage-auth-aad

【讨论】:

    【解决方案2】:

    对于 v12 Storage JS SDK,您可以从 @azure/core-auth 实现 TokenCredential 接口

    /**
     * Represents a credential capable of providing an authentication token.
     */
    export interface TokenCredential {
      /**
       * Gets the token provided by this credential.
       *
       * @param scopes The list of scopes for which the token will have access.
       * @param options The options used to configure any requests this
       *                TokenCredential implementation might make.
       */
      getToken(scopes: string | string[], options?: GetTokenOptions): Promise<AccessToken | null>;
    }
    

    一个简单的例子:

    const { ContainerClient } = require("@azure/storage-blob");
    
    const url = "<url to container>";
    
    function TestTokenCredential() {
      return {
        getToken: function (_scope, _opts) {
          return {
            token: "<access token>",
            expiresOnTimestamp: Date.now() + 60 * 60 * 1000,
          };
        },
      };
    }
    
    const containerClient = new ContainerClient(url, new TestTokenCredential());
    
    async function main() {
      for await (const blob of containerClient.listBlobsFlat()) {
        console.log(blob.name);
      }
    }
    
    main().catch((error) => {
      console.error(error);
    });
    

    【讨论】:

      猜你喜欢
      • 2015-02-23
      • 2020-06-09
      • 2020-10-05
      • 1970-01-01
      • 1970-01-01
      • 2019-02-18
      • 2017-07-26
      • 2011-07-12
      • 1970-01-01
      相关资源
      最近更新 更多