如何解决是否可以在 Azure 函数和 Azure Web API 之间启用托管标识?
我目前在 Basic
和 Azure Function
之间使用 Web API
身份验证。这并不安全,因此我正在寻找替代方案并在 Azure 中找到了 managed identity
功能。但是,我没有看到可以在 Web API 和 Azure 函数之间启用此功能。
注意:我们可以在 Azure Function
和 KeyVault
之间启用,但不能在 Web API 和 azure 函数之间启用。
正在寻找类似下面的解决方案
解决方法
因此我们需要获取此资源的访问令牌以调用 API,只需尝试以下代码(我假设您已为您的函数启用托管身份):
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static async Task<IActionResult> Run(HttpRequest req,ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var endpoint = Environment.GetEnvironmentVariable("IDENTITY_ENDPOINT");
var identity_header = Environment.GetEnvironmentVariable("IDENTITY_HEADER");
//chnage your client ID value here.
var resource = "4df52c7e-3d6f-4865-a499-cebbb2f79d26";
var requestURL = endpoint + "?resource=" + resource + "&api-version=2019-08-01";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("X-IDENTITY-HEADER",identity_header);
HttpResponseMessage response = await httpClient.GetAsync(requestURL);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var access_token = JsonConvert.DeserializeObject<TokenResp>(responseBody).access_token;
//After get access token for app: 4df52c7e-3d6f-4865-a499-cebbb2f79d26,call the API that protected by it
//chnage your api url here.
var APIURL = "https://frankapp.azurewebsites.net";
HttpClient callAPI = new HttpClient();
callAPI.DefaultRequestHeaders.Add("Authorization","Bearer "+ access_token);
HttpResponseMessage APIResponse = await callAPI.GetAsync(APIURL);
//check the response code to see if called the API successfully.
return new OkObjectResult(APIResponse.StatusCode);
}
public class TokenResp {
public string access_token { get; set; }
public string expires_on { get; set; }
public string resource { get; set; }
public string token_type { get; set; }
public string client_id { get; set; }
}
结果:
,嗨,我可以看到您在询问 Azure Function
和 Web API
之间的交换,理论上应该是您的资源服务器(Apis)而不是托管身份。在 Azure AD 之上有关于代表身份验证/客户端授予凭据的概念。你可以按照这个学习教程 Build Azure functions with Microsoft Graph ,并开始思考你希望你的身份流看起来如何 - 简单的方法是代表使用 azure 函数和 web api,访问令牌断言在公共类中实现
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。