Cloud + IoT + Devices + Mixed Reality

AspNetCore.TestHost + Azure Active Directory (Part II)

So in my last post on the topic, I was describing some challenges I faced when receiving 401 not authorized errors when attempting to pass a seemingly correct bearer token to my Azure Active Directory protected WebAPI. I’ve discovered the solution. Not only was I able to get it working but it also works flawlessly on Azure Active Directory B2C (which was ultimately my end goal in testing).

It seems that I was missing a key aspect of my Test Server setup. Previously, I was following the documentation found here where they show you how to use a startup class. I thought that was all the configuration that was needed but it wasn’t. I got that impression because I was getting 401 not authorized errors I, falsely, believed that Azure Active Directory had been setup. It turns out that it had but it hadn’t.

It’s true the Startup class in my ASP.NET Core project does appear to add authentication as you can see in the screen shot above. However, when running on the TestServer, nothing can be taken for granted, not even appsettings.json. This file houses the configuration that the WebAPI uses to authenticate itself with Azure Active Directory. If this file is not loaded, you are going to be in a world of hurt.

The audience is a critical configuration variable for Azure AD because whatever is in the audience needs to match up with what the Bearer Token has been issued for. As you can see in the Azure Active Directory bits, we are pulling the Client ID out of that appsettings.json file and using it as the audience.

This is critical because when I request a bearer token I’m making the request to the “Native app”. You know, the one that has delegated permissions to the “Web API / Web App”. The Client ID for the Web API app is used as the ‘resource’. In OAuth, the resource is essentially what you are requesting authorization to. The authorization endpoint will verify that your credentials (depending on the grant type) are valid and that you are authorized to access the resource you specified.

What was happening was that Azure Active Directory was being added to my WebAPI that was hosted on the in-memory Test Server, however, the audience and authority were not configured properly because their configuration must be explicitly loaded onto the Test Server using the WebHostBuilder.

Adding this small change, loaded the appropriate Azure Active Directory settings which allowed my WebAPI to be properly configured with the right Audience and Authority specified. This meant that the bearer token that I correctly issued using the HTTP POST to the OAuth2 Token endpoint was able to be verified and accepted. Which ultimately allowed me to write automated integration tests hitting WebAPIs protected by Azure Active Directory and Azure Active Directory B2C.