In the ASP. NET core Web API Integration test article, I introduced the integration test for the ASP. NET core Web API.
Where I used the test-specific startup class, there were some differences in the configuration and development, such as removing the middleware associated with user authentication.
However, some of the tested behaviors require identity/authorization information.
So this article describes the use of bearer token as the authorization header when sending requests in the API integration test.
Using bearer tokens in integration testing
I used identity Server 4 for this project, and it might be inconvenient to use Identity server 4 for integration testing, so I decided to simplify and limit the work to only two projects in the API and test project.
First, add the authorization/authentication middleware for the tested system and modify the Startupintegrationtest:
In the Configureservices () method, you first add a permission policy that requires all MVC controllers to be accessible only to authorized users.
The authentication middleware is then added using Addauthentication () and set bearer as a scheme, with some parameter configurations through Addjwtbearer ().
A secret is needed here, because the test project will be used, so I'm going to make it a static property for the time being.
Finally, the middleware can be used in the Configure () method.
To the Testserverfixture class of the integration Test project, the first thing to do is to use the above secret to generate tokens, and set the authorization header in HttpClient:
You can set the identity Claims in the code that generates tokens. I've only added name and role here.
Then we try to find an integration test to debug, I use Vscode, click on the method above the debug:
I added some silly code to the test method to debug the user information:
View claims:
You can see that the identity claims has been set in the test code, indicating that the use of bearer token was successful.
Testing the authentication middleware
The tested system uses identity middleware: apps. Useranthentication (), we can also test the functionality of this middleware, if the token is incorrect, you should return to the 401 Unauthorized status code:
The test code is simple enough to set an incorrect token, and the Assert return status code is 401.
The test will pass:
The article is a little short and is introduced here.
Using Bearer tokens in the ASP. NET Core Web API integration test