简体   繁体   中英

Calling Azure function in C# client with AAD authentication

I've created a sample Azure Function, nothing complex, just a simple Hello, World. An App has been registered with AAD and the function has been configured for AAD Authentication and Authorization Level is set to Anonymous. Using a browser I can navigate to the function URL, be asked to login and get results as expected. When using a C# client, after getting a token (which is the same as the one used in the browser) I get 401 Unauthorized result. I've also tried Postman with the same results; 401 "You do not have permission to view this directory or page."

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();

Obviously I'm missing some configuration but can't seem to find what the issue is.

I didn't reproduce your issue on my side. Here are my steps for your reference.

1.Create a function with http trigger

在此处输入图像描述

2.Enable App Service Authentication by using Express mode.

在此处输入图像描述

3.Call the function url using 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.See the result in vs

在此处输入图像描述

The only difference in the code is that I used Result to get the result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM