Azure身份访问Blob存储

时间:2020-08-11 17:12:20

标签: java azure-active-directory azure-storage-blobs

我在访问我的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,但遇到了同样的问题。我为我的帐户设置了Storage 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);

2 个答案:

答案 0 :(得分:1)

您应将 Blob存储贡献者角色分配给与您的Azure AD应用程序关联的服务主体。

enter image description here

更新:

不确定为什么Authenticate with Azure Identity对您不起作用。

但是,如果您使用sasToken,请确保您具有足够的权限。

enter image description here

请参考我的代码:

    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的开头。

答案 1 :(得分:0)

所以所有代码都是正确的。我谈到了MS Azure支持。我错过了设置应用程序许可的权限。我错误地设置了用户名权限。像往常一样,一个简单的解决方法

所以现在同时使用secretKey和SAS工作

相关问题