【问题标题】:Use Managed Identity to allow Azure Function App to make Http Request to Azure App Service使用托管标识允许 Azure Function App 向 Azure App Service 发出 Http 请求
【发布时间】:2021-01-26 21:22:43
【问题描述】:

我有一个 Azure 函数应用程序、一个 Azure 应用程序服务和一个 Azure 存储帐户。该函数使用 HttpClient 向 Azure 应用服务上的 ASP.NET MVC 操作之一发出 GET 请求。在 App Service 和 Function App 中,我已经转到 Azure 门户中的 Identity 刀片并启用了系统标识。我不清楚我需要执行哪些额外配置才能允许函数应用被授权调用托管在应用服务上的 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);
}

我收到的错误信息是:

参数:连接字符串:[未指定连接字符串],资源:https://MYCUSTOMURL,权限:。异常消息:尝试使用托管服务标识获取令牌。无法获取访问令牌。重试 5 次后失败。 MSI ResponseCode: InternalServerError, Response: {"exceptionMessage":"AADSTS500011: 在名为 MYAZURETENANT 的租户中找不到名为 https://MYCUSTOMURL 的资源主体。如果租户管理员尚未安装应用程序或租户中的任何用户都同意。你可能已将身份验证请求发送给错误的租户。\r\n跟踪 ID: 4f401265-9163-45de-bce9-4744ce633d00\r\n相关 ID: 3e312f90-3ea6-45a4-87d4- 36416d1b19f0\r\n时间戳:2020-10-12 14:26:00Z","errorCode":"invalid_resource","serviceErrorCodes":["500011"],"statusCode":400,"message":null,"correlationId ":"e5f8c439-97a6-462f-a3b9-32b167b9057a"}

为了隐私,我当然已经替换了我的应用自定义域和租户 ID。

【问题讨论】:

    标签: asp.net-mvc azure azure-functions azure-managed-identity


    【解决方案1】:

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

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

    1、暴露你的web应用的api:

    2、将功能aad app添加到app服务aad app的范围内:

    3,然后在function中修改你的代码,使用azure function service prcipal获取token:

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

    【讨论】:

    • 好的,到此,我想我有一个更根本的问题。如果我从浏览器发出请求,我的请求就有效。但是,如果我从函数应用程序中创建它,即使在我删除操作上的 Authorize 标记后,它也会失败并显示 Not Found。
    猜你喜欢
    • 2022-10-24
    • 1970-01-01
    • 2022-01-04
    • 2020-02-27
    • 2017-07-15
    • 1970-01-01
    • 2018-09-15
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多