簡體   English   中英

使用托管服務身份對Azure功能進行授權以從Azure存儲容器中獲取Blob

[英]Authorization for Azure Function using Managed Service Identity to fetch blob from Azure Storage container

當我嘗試使用系統分配的托管身份在Azure Function應用程序中調用Azure Function從Azure存儲容器中獲取Blob時,遇到了:

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

我正在調整此處概述的方法。

這是代碼:

[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的整個存儲帳戶的Storage Blob數據貢獻者角色。

我工作了。 正如Rohit所注意到的那樣,已刪除的Blob完整路徑(如最初發布的那樣)錯誤地指定了Azure函數路徑而不是存儲帳戶路徑。 我后來解決了這個問題。 不過,在實施過程中我確實有錯別字。 更正路徑可以解決此問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM