ASP.NET Core Swagger Documentation with Bearer Authentication
Tags: authentication, dotnet, dotnetcore, swagger
Published: 2022-01-15 13:01:48

---
title: ASP.NET Core Swagger Documentation with Bearer Authentication
published: true
date: 2022-01-15 08:55:26 UTC
tags: authentication,dotnet,dotnetcore,swagger
canonical_url: 
---

_Originally published at_ [_https://eduardstefanescu.dev_](https://eduardstefanescu.dev/2022/01/15/asp-dotnet-core-swagger-documentation-with-authentication/) _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/2020/04/11/jwt-authentication-with-symmetric-encryption-in-asp-dotnet-core/)
- [https://eduardstefanescu.dev/2021/08/25/asp-dotnet-core-swagger-documentation/](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](https://www.nuget.org/packages/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.

```csharp
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](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<OpenApiSecurityScheme, IList> 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].](https://eduardstefanescu.dev/2022/01/15/asp-dotnet-core-swagger-documentation-with-authentication/#reference1)

```csharp
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]](https://eduardstefanescu.dev/2022/01/15/asp-dotnet-core-swagger-documentation-with-authentication/#reference2) [[3](https://eduardstefanescu.dev/2022/01/15/asp-dotnet-core-swagger-documentation-with-authentication/#reference3)].

### The result

The Swagger Documentation API page, can be accessed locally using the following URL: [http://localhost:5000/swagger/index.html](http://localhost:5000/swagger/index.html). In the top part of this page, you will notice the “Authorize” button, as in the picture below.

![](https://cdn-images-1.medium.com/max/1024/0*_NfkubVYL0L1m7dO.png)

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.

![](https://cdn-images-1.medium.com/max/1024/0*kSDNhFRFsAOYbFJB.png)

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.

![](https://cdn-images-1.medium.com/max/661/0*tn0JVg6YpAy_5a0n.png)

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.

![](https://cdn-images-1.medium.com/max/1024/0*w-c5XjgU942t_SLE.png)

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](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

[1][https://github.com/microsoft/OpenAPI.NET/tree/master](https://github.com/microsoft/OpenAPI.NET/tree/master)

[2][https://github.com/microsoft/OpenAPI.NET/blob/master/src/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs](https://github.com/microsoft/OpenAPI.NET/blob/master/src/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs)

[3][https://github.com/microsoft/OpenAPI.NET/blob/master/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs](https://github.com/microsoft/OpenAPI.NET/blob/master/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs)