简体   繁体   English

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

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

We are building a nodejs server, which authenticates the user using AAD .我们正在构建一个nodejs服务器,它使用AAD对用户进行身份验证。 We get a JWT accessToken from the Microsoft login endpoint when a user logs in to our app.当用户登录到我们的应用程序时,我们会从 Microsoft 登录端点获取JWT accessToken

How do we use this token to make calls to get the blobs/containers using this javascript API?我们如何使用此令牌调用以使用此 javascript API 获取blob/容器 I don't want to make direct ajax requests to the API's using the ( Authorization: Bearer accessToken ) calls.我不想使用 ( Authorization: Bearer accessToken ) 调用直接向 API 发出 ajax 请求。

I have succeeded in using postman like this to make the calls?我已经成功地使用这样的邮递员拨打电话了吗? How do I do this programmatically using blobServiceClient ?如何使用blobServiceClient编程方式执行此blobServiceClient

在此处输入图片说明

According to my research, if we use V10 version SDK @azure/storage-blob we can directly use Azure AD access token to manage azure blob service.根据我的研究,如果我们使用 V10 版本的 SDK @azure/storage-blob 我们可以直接使用 Azure AD 访问令牌来管理 azure blob 服务。 Because the sdk provides class TokenCredential .因为 sdk 提供了类TokenCredential We can use code const tokenCredential = new azure.TokenCredential("token") to initialize a credential then use it to get blob.我们可以使用代码const tokenCredential = new azure.TokenCredential("token")来初始化凭证,然后使用它来获取 blob。

for example例如

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

For more details, please refer to https://www.npmjs.com/package/@azure/storage-blob/v/10.5.0 and https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-nodejs-legacy .有关更多详细信息,请参阅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

Besides, please note that if you want to access azure blob with Azure AD, we need to assign RABS role (Storage Blob Data Owner Storage Blob Data Contributor or Storage Blob Data Reader) to user or service principal : https://docs.microsoft.com/en-us/azure/storage/common/storage-auth-aad此外,请注意,如果您想使用 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

For v12 Storage JS SDK you would implement the TokenCredential interface from @azure/core-auth对于 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>;
}

An simple example:一个简单的例子:

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.

相关问题 无法使用 azure-sdk-for-js 使用 Angular 访问 Azure Data Lake Gen2 的文件系统 - Unable to access FileSystem of Azure Data Lake Gen2 with Angular using azure-sdk-for-js 无法使用 Preview 4 azure-sdk-for-js 创建ChatThread() - Can't createChatThread() with Preview 4 azure-sdk-for-js 使用 JWT accessToken 在 azure-sdk-for-js 中创建 blobServiceClient - Creating a blobServiceClient in azure-sdk-for-js with JWT accessToken 在 Azure Pipeline 中为 HTTP 对象处理不记名令牌 - Handling Bearer Tokens in Azure Pipeline for HTTP Objects 使用不记名令牌时,带有 AD 身份验证的 Azure 函数导致 401 Unauthorized - Azure Function with AD auth results in 401 Unauthorized when using Bearer tokens 使用延续标记对 Azure CosmosDB 和 Python SDK 进行分页 - Paginating Azure CosmosDB with Python SDK using continuation tokens 使用 Bearer toke 授权 Azure 请求? - Authorize Azure Requests using Bearer toke? 如何从 Azure SDK DefaultCredential 获取不记名令牌 - How to get bearer token from Azure SDK DefaultCredential Azure使用节点js Sdk创建虚拟机 - Azure creating virtual machine using node js Sdk 使用Azure存储Node.JS SDK获取上传进度 - Get upload progress using Azure Storage Node.JS SDK
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM