使用 Managed Identity 允许 Azure Function App 向 Azure App Service 发出 Http 请求

Use Managed Identity to allow Azure Function App to make Http Request to Azure App Service

我有一个 Azure Function App、一个 Azure App Service 和一个 Azure 存储帐户。该函数使用 HttpClient 向 Azure 应用服务上的 ASP.NET MVC 操作之一发出 GET 请求。在 App Service 和 Function App 中,我都转到 Azure Portal 中的 Identity blade 并启用了系统身份。我不清楚我需要执行哪些额外配置才能允许 Function App 被授权调用应用服务上托管的 ASP.NET MVC 应用中托管的操作。

在ASP.NET Core 3.1 App中,我有一个非常典型的Startup.cs配置方法:

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
});

这是我希望 Function App 向其发出 GET 请求(它生成 PDF)的控制器操作签名:

[Authorize]
[Route("/GenerateFile")]
public async Task<IActionResult> GenerateFile(string id, double customerId, string version)

然后在 Azure 函数应用程序(第 3 版函数应用程序)中,这是我尝试发出 HTTP GET 请求的地方。

try
{
    var azureServiceTokenProvider = new AzureServiceTokenProvider();
    string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(reportReviewURL);
    _http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

    // Generates the Final PDF file that is then saved to Azure Storage in the orders container. This is what is served to the customer. 
    var response = await _http.GetAsync(reportReviewURL + "GenerateFile?version=Final&customerId=" + reportOrder.CustomerId + "&id=" + id);
    response.EnsureSuccessStatusCode();
}
catch (HttpRequestException ex)
{
    log.LogInformation("HttpRequestException thrown: " + ex.Message);
}

我收到的错误消息是:

Parameters: Connection String: [No connection string specified], Resource: https://MYCUSTOMURL, Authority: . Exception Message: Tried to get token using Managed Service Identity. Access token could not be acquired. Failed after 5 retries. MSI ResponseCode: InternalServerError, Response: {"exceptionMessage":"AADSTS500011: The resource principal named https://MYCUSTOMURL was not found in the tenant named MYAZURETENANT. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.\r\nTrace ID: 4f401265-9163-45de-bce9-4744ce633d00\r\nCorrelation ID: 3e312f90-3ea6-45a4-87d4-36416d1b19f0\r\nTimestamp: 2020-10-12 14:26:00Z","errorCode":"invalid_resource","serviceErrorCodes":["500011"],"statusCode":400,"message":null,"correlationId":"e5f8c439-97a6-462f-a3b9-32b167b9057a"}

为了隐私,我当然更换了我的应用程序自定义域和我们的租户 ID。

首先,如果你想使用MSI身份,那是不可能的。

这是因为 MSI 不支持公开 API。我们需要使用通用应用程序注册。

1,公开您的网络应用程序的api:

2、将函数aad app添加到app service aad app的作用域中:

3、然后在function中改代码,使用azure function service pricipal获取token:

https://docs.microsoft.com/en-us/azure/key-vault/general/service-to-service-authentication#connection-string-support