5

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?

2d1b
  • 595
  • 1
  • 6
  • 24

2 Answers2

0

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.

Tony Ju
  • 14,891
  • 3
  • 17
  • 31
  • it doesn't work I still get the 401 unauthorized after changing the scopes – 2d1b May 29 '20 at 10:22
  • @alexbf How did you call the function? Will the function url work in the browser? – Tony Ju May 30 '20 at 02:00
  • I call my function from Postman (I added some details in the post). The function will not work from a browser as it is configured to be called from a NativeApp – 2d1b May 31 '20 at 17:50
0

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

2d1b
  • 595
  • 1
  • 6
  • 24