Interaction testing is an important part of building good reliable software. And this doesn’t change when moving to the cloud. What does change is how you approach it. Recently I worked on a project where we used Azure Active Directory for authentication. Even Free edition, which is included with an Azure subscription, gives developers a quick and easy option to protect their web apps and APIs. In this blog post, I’d like to share one approach to testing APIs that uses Azure Active Directory for authentication.
Setting up Azure AD
The “Getting Started” page in your Azure AD portal page, as well as Microsoft documentation, provide a good description of how to setup Azure AD and integrate your application. Here’s the basic steps:
- Go to “App Registrations” and create an application. Note Client ID and Tenant ID — those will be used later.
- Once application is created go to “Authentication” section and select ID tokens in “Advanced settings”.
- Go to “API permissions” and grant admin consent for default directory. That will make sure all the users you create for interaction testing will be able to use this application.
- Go to “Certificates and secrets” and create new client secret. Save it somewhere as it’ll be used later.
- Go back to Azure AD > Users and create a user that will be used in our tests. As users are created with a temporary password, finish user setup by logging in with it to Azure portal and selecting a new password.
Then let’s create the API in Visual Studio 2017. I used the default API template for an ASP.NET Core app as a starting point. Code that enables Azure AD is taken straight from the application’s QuickStart page in Azure portal.
As this post’s main goal is how to test said API, I’m going to focus on what needs to be added to enable interaction testing. You can see the full source code here on GitHub.
Create a Custom Test Factory
First thing is to create custom test factory by inheriting from WebApplicationFactory:
Create a Token Controller
Let’s create a TokenController in our API that would take care of this flow:
Let’s also create appsettings.TestAutomation.json where we store configuration parameters for the environment used by interaction tests:
Let’s create a sample DataController that is protected by Authorize attribute:
Finally let’s create interaction tests — one to test a protected endpoint without a token and one with an authenticated user:
And an extension method to call API’s token endpoint:
As you can see, creating interaction tests for API using Azure AD is quick and easy. You can turn it into true end-to-end testing by creating a test automation environment for your data sources and other services, or you can mock those services and repositories inside your tests and just focus on testing the controller’s logic. Those tests could be run as part of pull requests or in CI environment as part of regression testing.
Again, full source code could be found here.