问题
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
?
回答1:
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
来源:https://stackoverflow.com/questions/59772186/using-bearer-tokens-along-with-azure-sdk-for-js