简体   繁体   中英

Using Bearer tokens along with azure-sdk-for-js

We are building a nodejs server, which authenticates the user using AAD . We get a JWT accessToken from the Microsoft login endpoint when a user logs in to our app.

How do we use this token to make calls to get the blobs/containers using this javascript API? I don't want to make direct ajax requests to the API's using the ( Authorization: Bearer accessToken ) calls.

I have succeeded in using postman like this to make the calls? How do I do this programmatically using 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. Because the sdk provides class TokenCredential . We can use code const tokenCredential = new azure.TokenCredential("token") to initialize a credential then use it to get 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 .

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

For v12 Storage JS SDK you would implement the TokenCredential interface from @azure/core-auth

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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