Search code examples
azureactive-directoryazure-active-directoryopenid-connectazure-api-apps

AAD API Role Based Authentication


I've succesffully created a web API that's hosted in Azure and secured using AAD bearer token authentication to allow a client application (currently just a test console app I built) to access it.

A requirement has come to light that users of the eventual client application (Sharepoint) will fall into 2 separate groups - access to certain areas of the API will be restricted for one of them.

My boss has stipulated that the API should handle all authentication so I need to swap out the current Azure Active Directory Bearer Authentication middleware and replace it with (I think) Open Id Connect Authentication.

I'm having some difficulty in putting a solution together as I'm not really clear on how/if this will work. I've been looking at the provided sample however I don't see how I can utilize it. In the sample, the users log in to the site directly but in my setup they don't log in to the API, they log in to Sharepoint which then calls out - how can the API use the

[Authorize(Roles = "Admin")]

attribute when it doesn't have any concept of a "logged in user".


Solution

  • To call the api, you will need to provide the access token which contains the permissions.

    Here is the code snippet for your reference.

    // Because we signed-in already in the WebApp, the userObjectId is know
                    string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
    
                    // Using ADAL.Net, get a bearer token to access the TodoListService
                    AuthenticationContext authContext = new AuthenticationContext(AzureAdOptions.Settings.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
                    ClientCredential credential = new ClientCredential(AzureAdOptions.Settings.ClientId, AzureAdOptions.Settings.ClientSecret);
                    result = await authContext.AcquireTokenSilentAsync(AzureAdOptions.Settings.TodoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
    
                    // Retrieve the user's To Do List.
                    HttpClient client = new HttpClient();
                    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, AzureAdOptions.Settings.TodoListBaseAddress + "/api/todolist");
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
                    HttpResponseMessage response = await client.SendAsync(request);
    

    Reference:

    Call a web API in an ASP.NET Core web app using Azure AD

    How to: Add app roles in your application and receive them in the token

    Using groups vs using application roles for authorization in Azure AD apps