【问题标题】:How to generate user delegation SAS for Azure Storage using Javascript SDK如何使用 Javascript SDK 为 Azure 存储生成用户委托 SAS
【发布时间】:2023-03-03 02:38:02
【问题描述】:

我正在尝试将文件上传到 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。

【问题讨论】:

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


    【解决方案1】:

    我怀疑这是权限问题

    在仔细分析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 角色添加到您的预期用户并尝试再次运行代码。

    【讨论】:

    • 但是为什么我可以使用 Azure 存储资源管理器上传。 Explorer 使用与我的小程序相同的登录名。可能来自DefaultAzureCredentialaz login 的access_token 缺少某些东西...?
    • 您是否已分配此权限?查看此 MS 文档:docs.microsoft.com/en-us/azure/storage/blobs/…。另外,检查您是否在 js 代码中设置了类似 SetPermissions 的权限:docs.microsoft.com/en-us/azure/storage/blobs/…
    • 没有。但我没有改变任何角色,因为这就是问题的全部动机:我不想改变角色。而且必须有一种方法,因为它可以在存储资源管理器中使用。 Azure 存储资源管理器知道如何为我的用户生成 SAS,而不需要任何特殊角色。但是感谢您再次询问;)
    • 你可以尝试使用 Https 吗:docs.microsoft.com/en-us/rest/api/storageservices/…
    • 根据文档,Owner 角色是不够的:docs.microsoft.com/en-us/rest/api/storageservices/… 以下角色应该起作用:贡献者、存储帐户贡献者、存储 Blob 数据贡献者、存储 Blob 数据所有者、存储 Blob 数据读取者和存储 Blob 委派者。从 Azure 存储资源管理器复制的 SAS 使用帐户密钥进行保护,它与用户委托 SAS 不同。 docs.microsoft.com/en-us/azure/storage/common/…
    猜你喜欢
    • 2020-03-08
    • 1970-01-01
    • 2021-05-12
    • 2021-08-15
    • 1970-01-01
    • 2019-10-16
    • 2015-04-23
    • 2021-10-02
    • 2020-08-26
    相关资源
    最近更新 更多