ASP.NET Web API / OWIN authenticated integration tests without authorization server
/ 4 min read
Integration testing of OWIN Web API services is super easy with the MIcrosoft.Owin.Testing.TestServer component. It is basically an in-memory OWIN host that runs together with the HttpClient without needing any network calls.
Authentication
Aaron Powell has written an extensive post about to test Web API services that require OAuth token authentication. With the method described in this post, tokens are requested from the /token resource (provided by the OWIN OAuth Authorization Server) before executing the actual API. This method works great for situations where the Web API service that is being tested also contains the authorization server. But sometimes the Web API service under test doesn’t contain the authorization server, so authentication tokens have to be requested from an external authorization server. This highly complicates the integration tests because the external server has to be setup for the tests. It would be great if we could get an authorization token for tests without the need for an external authorization server.
Generate an OAuth token without authorization server
To generate and use a token in the integration tests, we create a base class (BaseAuthenticatedApiTestFixture) for our authenticated test fixtures that borrows some of the logic of the Owin OAuthAuthorizationServerMiddleware internals. This base class inherits again from BaseApiTestFixture. This class contains all logic for creating the Owin TestServer and calling the API and is very much inspired by the BaseServerTest class in Aaron Powell’s post.
The GenerateToken() method in the code above creates the token in three steps:
- Create a ClaimsIdentity that contains the username and claims (like roles);
- Create an AuthenticationTicket based on the ClaimsIdentity;
- Convert the AuthenticationTicket into a token with the TicketDataFormat class that uses a DataProtector to encrypt the ticket.
To make sure the token is accepted by the Owin OAuthBearer middleware, the DataProtector in step 3 needs to be the same as the one that is used for decrypting the token. Luckily we can create one during initialization of the Owin TestServer. This is set in a protected property of the BaseApiTestFixture so we can access it in BaseAuthenticatedApiTestFixture the subclass:
Testing
To execute authenticated tests, just inherit from BaseAuthenticatedApiTestFixture and call the test methods in the base class. This is the controller we’re testing:
As you can see, there are Authorize attributes that require authorization. The actual test code (using XUnit) is super simple:
Example solution
Check out the complete example solution at https://github.com/martijnboland/AuthenticatedOwinIntegrationTests