使用托管服务身份从Azure存储容器中获取Blob的Azure功能授权

时间:2019-05-24 00:34:49

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

当我尝试使用系统分配的托管身份在Azure Function应用程序中调用Azure Function来从Azure Storage容器中获取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功能应用程序具有系统分配的托管身份,该身份对于目标Blob的整个存储帐户具有存储Blob数据贡献者角色。

1 个答案:

答案 0 :(得分:0)

我已经开始工作了。正如Rohit所注意到的那样,已删除的Blob完整路径(如最初发布的那样)错误地指定了Azure函数路径而不是存储帐户路径。我后来解决了这个问题。不过,在实施过程中我确实有错别字。更正路径可以解决问题。