如何使用 Javascript SDK 为 Azure 存储生成用户委派 SAS

时间:2021-01-20 07:39:58

标签: javascript node.js azure azure-storage azure-sdk

我正在尝试将文件上传到 Azure Blob 存储。到目前为止我所做的:

npm i @azure/identity @azure/storage-blob

使用用户委托键生成 SAS 查询参数:

async function generateSas() {
    const startDate = new Date();
    const expiryDate = new Date();
    startDate.setTime(startDate.getTime() - 100 * 60 * 1000);
    expiryDate.setTime(expiryDate.getTime() + 100 * 60 * 60 * 1000);

    const credential = new DefaultAzureCredential();
    const blobServiceClient = new BlobServiceClient(STORAGE, credential);
    const key = await blobServiceClient.getUserDelegationKey(startDate, expiryDate);

    return generateBlobSASQueryParameters({
        containerName: CONTAINER,
        startsOn: startDate,
        expiresOn : expiryDate,
        permissions: ContainerSASPermissions.parse('rwl'),
    }, key, ACCOUNT).toString();
}

使用生成的SAS上传

async function upload(sasToken: string) {
    const blobClient = new BlockBlobClient(
      `https://${ACCOUNT}.blob.core.windows.net/${CONTAINER}/test.json?${sasToken}`);
    const content = 'some content';
    const response = await blobClient.upload(content, content.length);
}

在运行此之前,我会使用我的帐户进行 az login

错误:

(node:19584) UnhandledPromiseRejectionWarning: RestError: This request is not authorized to perform 
this operation using this permission. 

如果我使用相同的登录名从 Azure 存储资源管理器 复制 SAS,则代码有效!所以我假设有一些方法可以为我的帐户检索有效的 SAS。

1 个答案:

答案 0 :(得分:0)

我怀疑这是一个权限问题

在仔细分析 Can't list file system of azure datalake with javascriptManagedIdentityCredential failed when used to list blob containers #5539 问题后,我认为 Owner 角色不足以上传 Blob 存储帐户中的 Blob。您必须先使用 Storage Blob Data * 角色之一(例如 Storage Blob Data Owner,然后才能上传 Blob。

因此,请尝试向您的目标用户添加 Storage Blob Data Owner 角色,然后再次尝试运行代码。