如何在 azure 存储 blob 中生成许可下载链接

问题描述

我可以通过这些代码得到一个链接,它可以成功下载文件

BlobContainerSasPermission blobContainerSasPermission = new BlobContainerSasPermission()
                .setReadPermission(true)
                .setWritePermission(true)
                .setListPermission(true);
BlobServiceSasSignatureValues builder = new BlobServiceSasSignatureValues(OffsetDateTime.Now().plusDays(1),blobContainerSasPermission)
                .setProtocol(SasProtocol.HTTPS_ONLY);
BlobClient client = new BlobClientBuilder()
                .connectionString("connection string")
                .blobName("")
                .buildClient();
String blobContainerName = "test";
return String.format("https://%s.blob.core.windows.net/%s?%s",client.getAccountName(),blobContainerName,client.generateSas(builder));

但是每个人都可以通过这个链接下载文件,我希望文件可以被授权的人下载。是否有任何代码或 azure 的设置(例如 AD?)可以实现这一点?谢谢

-------------------------更新--------------------- ---

我找到了一个 doc,并且给出了一个原因。 注意:此方法调用仅在此对象的 HttpPipeline 中使用 TokenCredential 时有效。 但只有 BasicAuthenticationCredential 在我的导入包中实现了 TokenCredential。这是我的 mvn。

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-blob</artifactId>
    <version>12.11.0-beta.2</version>
</dependency>

我试过了

String userName = "userName";
String password = "password";
BasicAuthenticationCredential basicAuthenticationCredential = new BasicAuthenticationCredential(userName,password);
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().endpoint(endpoint).credential(basicAuthenticationCredential).buildClient();

然后我得到了这个状态代码 401,(InvalidAuthenticationInfo)

大神们帮帮我吧!

解决方法

用于访问容器、目录或 blob 的 SAS 令牌可能是 使用 Azure AD 凭据或帐户密钥进行保护。 SAS 使用 Azure AD 凭据进行保护称为用户委派 SAS。 Microsoft 建议您尽可能使用 Azure AD 凭据 作为安全最佳实践,而不是使用帐户密钥, 可以更容易受到损害。当您的应用程序设计需要 共享访问签名,使用 Azure AD 凭据创建用户 委派 SAS 以获得更高的安全性。

使用 UserDelegationKey

生成 SAS 查询参数

以下示例为 Azure 存储容器生成 SAS 查询参数。

BlobSasPermission blobPermission = new BlobSasPermission()
    .setReadPermission(true)
    .setWritePermission(true);

// We are creating a SAS to a container because only container name is set.
BlobServiceSasSignatureValues builder = new BlobServiceSasSignatureValues()
    .setProtocol(SasProtocol.HTTPS_ONLY) // Users MUST use HTTPS (not HTTP).
    .setExpiryTime(OffsetDateTime.now().plusDays(2))
    .setContainerName("my-container")
    .setPermissions(blobPermission);

// Get a user delegation key after signing in with Azure AD
UserDelegationKey credential = new UserDelegationKey();
String account = "my-blob-storage-account";
BlobServiceSasQueryParameters sasQueryParameters = builder.generateSasQueryParameters(credential,account);

查看 Create a user delegation SASthis 以了解实施详情。

,

似乎没有办法实现这一点。

This is the answer.