Azure 函数未使用用户分配的标识在 blob 存储中上传文件

Azure function is not uploading file in blob storage using user assigned identity

在函数应用程序和 blob 存储帐户中添加了用户分配的身份作为 "Storage Blob Data Contributor" 角色。代码在存储帐户中添加函数应用程序的出站 ip 地址时工作正常。但是想使用用户分配的身份。

我遇到错误 "One or more errors occurred. (This request is not authorized to perform this operation.)"

有人遇到过这个问题吗?提前感谢您的帮助。

            StorageCredentials storageCredential = new StorageCredentials(AccountName, AccessKey);
            CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredential, true);

            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer blobContainer = blobClient.GetContainerReference("rawzone");
            BlobRequestOptions requestOptions = new BlobRequestOptions() { RetryPolicy = new NoRetry() };
            CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference("test");

            string result = "writing test file " + DateTime.Now.ToString();
            blockBlob.UploadTextAsync(result).Wait();

我在自己的网站上进行了测试,效果很好。您可以参考以下步骤进行操作。

1.Create 我的用户分配的托管标识并将 Storage Blob Data Contributor 添加到标识中。

2.In azure 函数启用用户分配托管标识并添加您之前创建的用户标识。

3.In azure 函数 http 触发器和函数中的以下代码将 use user managed identity。您提供的代码正在使用存储凭证,它将始终正常运行。

AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://storage.azure.com/");
TokenCredential tokenCredential = new TokenCredential(accessToken);
StorageCredentials storageCredentials = new StorageCredentials(tokenCredential);
CloudBlobClient blobClient = new CloudBlobClient(new Uri("https://xxxxx.blob.core.windows.net"), storageCredentials);

CloudBlobContainer blobContainer = blobClient.GetContainerReference("container");
BlobRequestOptions requestOptions = new BlobRequestOptions() { RetryPolicy = new NoRetry() };
CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference("hello.txt");

string result = "writing test file " + DateTime.Now.ToString();
blockBlob.UploadTextAsync(result).Wait();

4.To 控制进程,使用传递给 AzureServiceTokenProvider 构造函数或在 AzureServicesAuthConnectionString 环境变量中指定的连接字符串。

单击您的用户身份并获取其应用程序 ID。

RunAs=App;AppId={ClientId of user-assigned identity}

5.Then 运行 azure 函数,它会将文本写入 blob。