azure - 使用托管服务标识对 Azure Function 进行授权以从 Azure 存储容器获取 blob

标签 azure azure-active-directory azure-functions azure-blob-storage

当我尝试使用系统分配的托管标识在 Azure Function 应用程序中调用 Azure Function 来从 Azure 存储容器中获取 blob 时,我遇到了:

System.Private.CoreLib: Exception while executing function:<FunctionName>. Microsoft.WindowsAzure.Storage: Unauthorized.

我正在采用概述的方法 here .

代码如下:

[FunctionName("TestFetchTileViaSvcPrinId")]
public static async Task<HttpResponseMessage> RunAsync(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    ILogger log) {
    log.LogInformation("C# HTTP trigger function processed a request.");

    const string blobName = "https://<storageaccount>.blob.core.windows.net/...path.../<file>.jpg";

    // Get the initial access token and the interval at which to refresh it.
    var azureServiceTokenProvider = new AzureServiceTokenProvider();
    NewTokenAndFrequency tokenAndFrequency = TokenRenewerAsync(azureServiceTokenProvider, CancellationToken.None).GetAwaiter().GetResult();

    // Create storage credentials using the initial token, and connect the callback function to renew the token just before it expires
    var tokenCredential = new TokenCredential(tokenAndFrequency.Token, TokenRenewerAsync, azureServiceTokenProvider, tokenAndFrequency.Frequency.Value);

    var storageCredentials = new StorageCredentials(tokenCredential);

    var cloudBlockBlob = new CloudBlockBlob(new Uri(blobName), storageCredentials);

    using (var memoryStream = new MemoryStream()) {
        await cloudBlockBlob.DownloadToStreamAsync(memoryStream);  // Unauthorized exception is thrown here
        var httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK) {
            Content = new ByteArrayContent(memoryStream.ToArray())
        };
        httpResponseMessage.Headers.Add("Cache-Control", "max-age=31536000"); //31536000 seconds ~ 1 year
        httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        return httpResponseMessage;
    }

}

Azure Function App 具有系统分配的托管标识,该标识对目标 Blob 的整个存储帐户具有存储 Blob 数据贡献者角色。

最佳答案

我成功了。正如 Rohit 所注意到的,经过编辑的 blob 完整路径(如最初发布的那样)错误地指定了 Azure 函数路径,而不是存储帐户路径。我随后解决了这个问题。尽管如此,我在实现的路径中确实有一个拼写错误。更正路径解决了问题。

关于azure - 使用托管服务标识对 Azure Function 进行授权以从 Azure 存储容器获取 blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56284486/

相关文章:

azure - 如何使用 MSAL 读取 ID token

azure - (可选)使用 Azure Function 生成输出

api - PowerApps调用Azure API应用程序

azure - Azure Blob Store 如何处理以 .gz 结尾的文件?

authentication - 通过 Azure OpenID Connect 进行联合身份验证

Azure B2C : Enable other devs to access B2C Tenant via their Microsoft Accounts

c# - 在 Azure Functions 中加载证书时出现运行时错误

python - 在azure上部署python Azure函数时出现“找不到模块”错误

Azure函数应用程序: Authentication Breaks Development Portal

azure - 服务总线 session ReceiveBatchAsync 仅接收 1 条消息