4
votes

My goal is to secure my Azure Functions with Azure AD and call them from a WPF application.

I have an Azure Function with the following definition :

public IActionResult Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)]
        HttpRequest req,
        ILogger log,
        ExecutionContext context,
        ClaimsPrincipal claimsPrincipal)

I registered an Azure AD App and configured the settings for Native App Authentication :

Azure AD App Registration Settings

I configured my app in the "Expose an API" bladd Expose an API

I also added an API Permissions

API Permission

I associated my app in my Azure Functions App in the Authentication / Authorization blade.

Azure Functions Authorization Settings

I am getting a token from Azure AD like this in a WPF app (using the Microsoft.Identity.Client library)

            string applicationID = "***"; // My AppID Guid
            PublicClientApp = PublicClientApplicationBuilder.Create(applicationID)
                .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
                .Build();

            var listScopes = new List<string>
            {
                //"user.read" - Removed based on @tony-yu recommendation
                $"api://{applicationID}/MyScope"
            };

            var authResult = await PublicClientApp.AcquireTokenInteractive(listScopes)
                                      .ExecuteAsync();

            var myToken = authResult.AccessToken;

I can authenticate without any problem and I am successfully getting a token but whenever I call my function and I provide my token in the Authorization header (Authorization = Bearer ****), I get :

401 - You do not have permission to view this directory or page.

Here's how I call it (Postman) :

enter image description here

Here is the WWW-Authenticate header content when the call returns

www-authentication

When I check the token I got, it seems legit

Token

Any idea what I am doing wrong?

2

2 Answers

0
votes

The scope is not correct. As you want to access your function which is protected by ad, you need to use

var listScopes = new List<string>
            {
                "{applicationID}/.default"
            };

instead.

user.read is the permission for Microsoft Graph API.

0
votes

So I finally made it work thanks to this SO article here by ambrose-leung