[英]Is it possible to enable Managed Identity between Azure function and Azure Web API?
所以我们需要为这个资源获取一个访问令牌来调用 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; }
}
结果:
Hi i can see you asking exchange between of Azure Function
and Web API
, in theory, it should be your resource server(Apis) rather than managed identity. 在 Azure AD 之上有关于代表身份验证/客户端授予凭证的概念。 You may follow this learning tutorial Build Azure functions with Microsoft Graph , and start thinking how would you want your identity flow looks like - simple way is to using on-behalf to azure functions and web api, the access token assertion are implemented in common classes对彼此而言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.