[英]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.