Configuring Authentication in Functional testing in ASP.NET WEB API

Configuring Authentication in Functional testing in ASP.NET WEB API


12 Articles


In this article, let's learn about how to setup Authentication in Functional Test in WebAPI in ASP.NET Core.

Note: If you have not done so already, I recommend you read the article on Using WireMock.NET in Functional testing in ASP.NET WEB API.

Table of Contents

  1. Introduction
  2. Setup Authentication
  3. Setup Authorization
  4. Summary


In our previous article we saw how to use WireMock.NET in functional test to validate HTTP calls. In this article, we will see how to setup Authentication and Authorization in functional test in WebAPI in ASP.NET Core step by step. We will be using the same project that we used in our previous article.

The straight forward way to enable Authentication and Authorization in Web API is to add UseAuthentication() middleware and decorate necessary endpoints with [Authorize] attribute. But instead of addiing to each Endpoint or to each Controller, we can do a small configuration in Program.cs by adding AuthorizeFilter and enable for all Endpoints globally.

Code Sample - Configure Authentication in Web API

Now after adding the above code in Program.cs, if we run our tests, all our tests will fail with 401 UnAuthorized as shown below.

Failing Tests after enabling Authentication Failed Test

Lets quickly verify if we are getting 401 UnAuthorized from swagger. Here is the swagger response from the WeatherForecast endpoint.

Swagger output from Endpoint to return values from API Swagger Response

Setup Authentication

Setting up Authentication in Functional Test is a bit tricky as it cannot be mocked like unit tests. But here is plan as per official documentation.

  1. Let's start with AuthenticationHandler.

    Code Sample - Configure Test Auth Handler for ASP.NET WEB API Functional Test

  2. When application is started in test host add new authentication scheme (let's call it Test).

    Code Sample - Register Test Authentication Scheme in Custom Web Application Factory

  3. Configure authentication scheme to use custom authentication handler (TestAuthHandler) that creates fake identity for integration tests. This handler creates fake user when HandleAuthenticateAsync() is called. We don't need any additional hacks to make ASP.NET Core application use this fake identity. Our integration test needs also some changes because of authentication handler.

  4. Extend test client to use authentication header with scheme Test.

    Code Sample - Setting Auth Header in Test HTTP Client

That's it now if we run our tests, it should pass. Here is the output of the test after adding the above code.

Authorize Passing Test Authorize Passing Test

Setup Authorization

So far so good. Now the problem with the above TestHandler is that it provides static set of claims for all the tests. This will not be the case in real world applications. The handler provides web application with static set of claims. No matter what is the request claims are always the same. This way it is not possible to test application with different users and roles. We need to validate Authorization for endpoints which require different set of claims. So we need to configure claims for each test. Here is the plan.

  1. To make test authentication handler support different user accounts I added claims provider. This is the class that carries given set of claims to test authentication provider. I added also some static methods to return already initialized provider with set of claims specific for role.

    Code Sample - Configuring Claims in ASP.NET WEB API Functional Test

  2. Inject above instance of claims provider to test authentication handler using framework-level dependency injection.

    Code Sample - Injecting claims and roles in APS.NET Web API Functional Test

That's it. Now we can use the above code to configure claims and roles for each test. Let's try to test both Guest and Admin role. Since we added AuthClaimsProvider.WithGuestClaims() as default in CustomWebApplicationFactory we can directly add that to GetWeatherForecastFromDatabase endpoint and run test.

Authorize Passing Test Guest Passing Test

Now lets try to test the Admin role on GetWeatherForecastFromAPI endpoint. For this we need to replace Guest claims with Admin claims. We are going to use the same Replace Service Method that we learned in Faking Dependencies in Functional testing in ASP.NET WEB API. The updated test code is shown below.

Code Sample - Running WEB API Functional Test with Admin Role

Thats it. We are done with setup. Now the tests will run in the following flow.

  1. Start Test Method.
  2. Create HTTP Client.
  3. Create WebApplicationFactory.
  4. Run Program.cs.
  5. Add Default Authentication / Override with Different Claims.
  6. Service Registration.
  7. Overriding Service Registration and Configuration with ConfigureTestServices.
  8. Build Web Application.
  9. WireMock.NET Setup.
  10. Test Code Execution.

Now lets run the test and see the result.

All Passing Test


In this article, we learnt about how to setup Authentication and Authorization in Functional Test in WebAPI in ASP.NET Core. We learnt how to setup Test Authentication Handler and Test Scheme and also learnt how to inject different users and claims in runtime. The complete source code for this article can be found here. With this we are completing the series on Functional Testing in ASP.NET WebAPI. I'm happy to share my knowledge on functional testing. Hope you enjoyed reading it.

  • Webapi
  • Authentication
  • Authorization
  • Functional Test
  • Integration Test