ASP.NET Core Swagger Documentation with Bearer Authentication
Eduard Stefanescu
Posted on January 15, 2022
Originally published at https://eduardstefanescu.dev on January 15, 2022.
In the previous article, we added Swagger Documentation to an existing ASP.NET Core project. This article will use the previous article and the JWT Authentication Symmetric Key source code to add to a project that already have Swagger Documentation the Authentication feature. These two article can be found here:
- https://eduardstefanescu.dev/2020/04/11/jwt-authentication-with-symmetric-encryption-in-asp-dotnet-core/
- https://eduardstefanescu.dev/2021/08/25/asp-dotnet-core-swagger-documentation/
The Swagger Documentation Authentication feature will be introduced briefly in the first section of this article, and its implementation will be discussed in the second section.
Introduction
As is described in the previous article, Swagger Documentation is a handy tool that generates documentation in a friendly manner from an XML file generated by the .NET Framework. But what if the described API has authentication, then the documentation should have it too. Swashbuckle.AspNetCore.SwaggerGen package provides the authentication feature, but this article will cover only the Bearer Authentication setup.
The Swagger Documentation web interface will act as a REST Client, by sending a request to the Authentication endpoint, receiving the Bearer Authentication Token, and then, with this token, we'll have to put it into an input box in order to set the authentication header for the next requests that we'll be making.
Adding the Security Definition
By specifying the security definition, Swagger will take into account that it will have to add the authorization feature. This feature consists of an “Authorize” button at the top of the page that will set the authorization header. The following code will be added in the AddSwaggerGen extension method of the SwaggerGen package.
options.AddSecurityDefinition(name: "Bearer", securityScheme: new OpenApiSecurityScheme
{
Name = "Authorization",
Description = "Enter the Bearer Authorization string as following: `Bearer Generated-JWT-Token`",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});
-
Name
refers to the name of the header; in this case, the request includes the Authentication header followed by the Bearer Token (i.e., Authorization: Bearer Generated-JWT-Token); -
Description
is used to help others understand how the authentication works and what value he or she has to enter in the input box; -
In
refers to the location of the ApiKey, which in this case will be in the Header. For other authentication types, there might be other options, like query or cookie; -
Type
is the security scheme that we'll be using; -
Scheme
is the RFC7235 Hyper Transfer Protocol, that will be used. In this case, we’ll be using the Bearer protocol, but this property also accepts all the other protocols that can be found here: https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml;
This five parameters are required in order to define how the security key will act.
Adding the Security Requirement
The AddSecurityRequirement extension method will add an authorization header to each endpoint when the request is sent. This method takes a dictionary of type Dictionary as a parameter, because the endpoints can have different authentication types (e.g. Basic, Saml). The value of the dictionary is a required list of scope names for the execution only if the security scheme is oauth2
or openIdConnect
. In our case, this list will be an empty one [1].
options.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Name = "Bearer",
In = ParameterLocation.Header,
Reference = new OpenApiReference
{
Id = "Bearer",
Type = ReferenceType.SecurityScheme
}
},
new List<string>()
}
});
The parameters above are required to setup the Security Requirement, but there are more. So Microsoft did a great job by defining all these fields and properties on the OpenAPI.NET GitHub page [2] [3].
The result
The Swagger Documentation API page, can be accessed locally using the following URL: http://localhost:5000/swagger/index.html. In the top part of this page, you will notice the “Authorize” button, as in the picture below.
This button will open a pop-up window, where we’ll enter the Bearer Token in order to set the Authorization header. But before doing this, let’s first get the JWT Token from the Authentication endpoint.
Authenticating
By opening the Authentication endpoint block from the Swagger Documentation, we can notice an open padlock in the top right corner of the endpoint, representing that there is no Authorization header set yet.
In this opened block, the Try Out button must be clicked in order to open the request section; where the valid username and password should be entered to generate the JWT Token. Otherwise the response code will be Unauthorized, or depending on your implementation it may not generate a valid Token.
In the picture above, we can see that after executing a valid request, the API responds with OK HTTP Status Code with a Body, that contains the needed Token.
Authorization
After generating the JWT Token, now this Token must be copied and we can return to the top of this page. Doing so, we should press the Authorize button, and a pop-up window should be displayed as in the picture below.
In the Value input box the Authorization header will be set. Firstly as is described in description we need to specify the security scheme, in this case Bearer and after that generated the JWT Token. Then press the Authorize button and close this window to test out if the authentication works.
Requesting an authorized resource
Now, after authenticating and authorization steps, we can test an endpoint that needs authorization. In this example, the WeatherForecast endpoint will be used. By opening it we can see, that the unlocked padlock is not locked, meaning that we are authorized.
In the picture above, is the response of the authorized endpoint. That returns the OK HTTP Status Code with all the available weather forecasts.
The source code from this article can be found on my GitHub account: https://github.com/StefanescuEduard/DotnetSwaggerDocumentation/tree/master/API.WithAuthentication.
Thanks for reading this article, if you find it interesting please share it with your colleagues and friends. Or if you find something that can be improved please let me know.
References
Posted on January 15, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.