繁体   English   中英

使用 Bearer 令牌和 azure-sdk-for-js

[英]Using Bearer tokens along with azure-sdk-for-js

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

我们如何使用此令牌调用以使用此 javascript API 获取blob/容器 我不想使用 ( Authorization: Bearer accessToken ) 调用直接向 API 发出 ajax 请求。

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

在此处输入图片说明

根据我的研究,如果我们使用 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/ blob/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

对于 v12 Storage JS SDK,您将实现来自@azure/core-authTokenCredential接口

/**
 * 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);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM