Member-only story
API Security in Swagger
How to configure security schemes for our API documentation in Swagger.

In my last article, Get Started with Swashbuckle and ASP.NET Core, we discussed how to configure Swashbuckle to document our APIs. Picking up from that, we are going to talk about configuring security schemes for our API documentation in this article.
For demo purposes, we will simulate a scenario that a web API project uses JSON Web Token (JWT) authentication and Basic authentication over HTTPS. The following screen recording shows the authorization processes in Swagger UI by using a generated JWT Bearer token and using a username and password.

In the screen recording, we can observe that once the credential (either a JWT Bearer token or a username and password) is saved, Swagger UI will pass an Authorization
header along with the HTTP requests, thus our web API endpoints can verify the permissions.
The full solution can be found in my GitHub repository. Now let’s discuss some implementation details.
Security Schemes in OpenAPI 3
OpenAPI 3 is the latest version of the OpenAPI Specification, which is also known as OAS3. In OAS3, we can describe the API protection using the following security schemes: (1) HTTP authentication schemes using the Authorization
header, such as Basic authentication and Bearer authentication; (2) API keys that are in headers, query strings or cookies; (3) OAuth 2; (4) OpenID connect Discovery. We can learn the specification details from the Swagger documentation (link), which explains about defining and applying security schemes, and describes the required and optional fields for each security scheme.
We can examine the security definitions from a swagger.json
document. The following screenshot shows an example swagger.json
file, which is generated by the library Swashbuckle.AspNetCore in our case.