[英]Calling Azure function in C# client with AAD authentication
我創建了一個示例 Azure Function,沒什么復雜的,只是一個簡單的 Hello, World。 應用程序已在 AAD 中注冊,並且已為 AAD 身份驗證配置 function,並且授權級別設置為匿名。 使用瀏覽器,我可以導航到 function URL,要求登錄並按預期獲得結果。 使用 C# 客戶端時,在獲取令牌(與瀏覽器中使用的令牌相同)后,我得到 401 Unauthorized 結果。 我也嘗試過 Postman ,結果相同; 401 “您無權查看此目錄或頁面。”
var clientCredential = new ClientCredential("16c17039-xxxx-4514-xxxx-fc68a97fxxxx", "00000009q_XwxPP]oyDo8UqZfAsxxxx");
AuthenticationContext context = new AuthenticationContext("https://login.microsoftonline.com/xxxxx.onmicrosoft.com", false);
AuthenticationResult authResult = await context.AcquireTokenAsync(
"16c17039-xxxx-4514-xxxx-fc68a97fxxxx",
clientCredential);
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
var response = await client.GetAsync("https://xxxx.azurewebsites.net/api/Sample?code=xxxxx");
response.EnsureSuccessStatusCode();
顯然我缺少一些配置,但似乎無法找到問題所在。
我沒有在我這邊重現您的問題。 這是我的步驟供您參考。
1.用http觸發器創建一個function
2.使用快速模式啟用應用服務身份驗證。
3.調用 function url 使用 C#
static void Main(string[] args)
{
var clientCredential = new ClientCredential("{app_client_id}", "{app_client_secret}");
AuthenticationContext context = new AuthenticationContext("https://login.microsoftonline.com/xx.onmicrosoft.com", false);
AuthenticationResult authResult = context.AcquireTokenAsync(
"{app_client_id}",
clientCredential).Result;
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
var response = client.GetAsync("https://tonytestad.azurewebsites.net/api/HttpTrigger1?code=LoyOi4C&name=123").Result;
response.EnsureSuccessStatusCode();
}
4.在vs中查看結果
代碼中唯一的區別是我使用Result
來獲取結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.