java - 对 Blob 存储的 Azure 标识访问
问题描述
我在访问我的 azure blob 存储时遇到了权限问题。
我的应用程序位于 Azure 外部,将访问 Azure Blob 存储以获取文件。
我已在 Azure AD 中注册了该应用程序并拥有一个密钥。秘密在 1 年内到期。
我已经设置了环境变量 AZURE_CLIENT_ID、AZURE_CLIENT_SECRET 和 AZURE_TENANT_ID。
BlobServiceClient storageClient = new BlobServiceClientBuilder()
.endpoint("https://myaccount.blob.core.windows.net")
.credential(newDefaultAzureCredentialBuilder().build())
.buildClient();
BlobContainerClient blobContainerClient = storageClient.getBlobContainerClient("mycontainer");
BlobClient blobClient = blobContainerClient.getBlobClient("Sample.pdf");
File destinationDir = new File("/somedir/");
File downloadedFile = new File(destinationDir, "Sample.pdf");
blobClient.downloadToFile(downloadedFile.getAbsolutePath(),true);
尝试下载时,我得到:
<Code>AuthorizationPermissionMismatch</Code><Message>This request is not authorized to perform
this operation using this permission.
RequestId:f0c2de14-401e-0050-0bfd-6f97ad000000
Time:2020-08-11T16:34:29.1943093Z</Message></Error>"
我承认我现在很困惑。我需要先获得令牌吗?我以为我拥有一切,因为示例非常明确,但是四处搜索我看到了有关获取令牌的引用,而有些则没有。
我也尝试过使用 SAS,但我遇到了同样的问题。我为我的帐户设置了存储 Blob 数据贡献者。
以下是使用 SAS 的连接示例
BlobServiceClient storageClient = new BlobServiceClientBuilder()
.endpoint("https://mystorageaccount.blob.core.windows.net/?sv=2019-
12-12&ss=b&srt=c&sp=rlx&se=2020-08-12T22:37:28Z&st=2020-08-
12T14:37:28Z&spr=https&sig=<mysig>")
.buildClient();
BlobContainerClient blobContainerClient =
storageClient.getBlobContainerClient("mycontainer");
BlobClient blobClient =
blobContainerClient.getBlobClient("Sample.pdf");
File destinationDir = new File("/mydir");
File downloadedFile = new File(destinationDir, "Sample.pdf");
blobClient.downloadToFile(downloadedFile.getAbsolutePath(),true);
解决方案
您应该将Blob 存储参与者角色分配给与您的 Azure AD 应用关联的服务主体。
更新:
不确定为什么使用 Azure Identity 进行身份验证对您不起作用。
但如果您使用 sasToken,请确保您拥有足够的权限。
请参考我的代码:
BlobServiceClient blobServiceClient = new BlobServiceClientBuilder()
.endpoint("https://allen3545635.blob.core.windows.net/")
.sasToken("sv=2019-12-12&ss=bfqt&srt=sco&sp=rwdlacupx&se=2020-08-13T15:18:15Z&st=2020-08-13T07:18:15Z&spr=https&sig=XXX")
.buildClient();
记得去掉“?” 在 Azure 门户上生成的 sasToken 的开头。