微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用托管身份允许Azure Function App向Azure App Service发出Http请求

如何解决使用托管身份允许Azure Function App向Azure App Service发出Http请求

我有一个Azure功能应用程序,一个Azure应用程序服务和一个Azure存储帐户。该函数使用HttpClient向Azure App Service上的ASP.NET MVC操作之一发出GET请求。在App Service和Function App中,我都转到了Azure Portal中的“身份”刀片,并启用了系统身份。我尚不清楚我需要执行哪些其他配置才能使功能应用程序被授权来调用由应用程序服务托管的ASP.NET MVC应用程序中托管的操作。

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

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

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

这是我希望功能应用程序发出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,响应:{“ 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。

解决方法

首先,如果您想使用MSI身份,则不可能。

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

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

enter image description here

2,将功能aad应用添加到应用服务aad应用的范围内:

enter image description here

3,然后在函数中更改代码,使用azure函数服务pricipal获取令牌:

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。