[英]Unable to access FileSystem of Azure Data Lake Gen2 with Angular using azure-sdk-for-js
[英]Using Bearer tokens along with azure-sdk-for-js
根据我的研究,如果我们使用 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.0和https://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-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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.