Use JWT authorization token in swagger .NET Core

In this article, we will learn to add a JWT authorization token in swagger .NET Core.

Today in this article, we will cover below aspects,

If interested, ASP.NET Core 3.1 or .NET 6 has brought new improvements for swagger with new breaking changes, please see here for more details,

Swagger or OpenAPI describe standards and specifications for RESTFul API description.

These specifications are an attempt to create a universal description for REST API. This specification provides the advantage of understanding the RESTFul services easily (especially if developers are consuming any new Web API ) plus helps provide easily ready documentation and details of capabilities an organization owns.

In our last article on JWT(JSON Web Token) Authentication in .NET Core, we learned about how to use JWT bearer token for securing .NET Core API.

Open API specification or Swagger V3.0 lets you define the different authentication types for an API like Basic authentication, OAuth2 Authentication, JWT bearer, etc.

In this post, we will see how to add JWT authorization to swagger documentation.

Adding swagger definition in .NET Core is simply a 2-3 steps process.

Let’s get started from scratch and quickly add basic swagger to the API and then add JWT to the API documentation.

1. Create a WebAPI sample service using NET Core

One can use any version of .NET Core like 2.1 or 2.2 etc.

Please add below Swashbuckle NuGet package to your WebAPI using a Command prompt or package manager console

Command: Install-Package Swashbuckle.AspNetCore

OR

This single NuGet package shall add all other required components as shown below and you need not have to add them explicitly,

  • Swagger
  • SwaggerUI
  • SwaggerGen
blank

2. Update ConfigureServices() method

Add below line to ConfigureServices() method as shown below,

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(
            {
                c.SwaggerDoc("v1", new Info { Title = "MyTestService", Version = "v1" });
            });
        }

3. Update Configure() method

Add below line to Configure() method as shown below,

app.UseSwagger();
app.UseSwaggerUI(
         {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "TestService");
          });

Let’s see swagger definition generated,

blank

If you come across any error, please see the article Failed to load API definition in Swagger for troubleshooting.

Please note that in .NET Core default swagger route used will be “/swagger/{documentName}/swagger.json” .

The swagger definition would give you an error like Failed to load API definition in Swagger if hosting in IIS or other cloud environments like Azure etc.

Add JWT Authorization to WebAPI

Please add methods AddSecurityDefinition () and AddSecurityRequirement() as shown below,

 c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
                {
                    Description = "JWT Authorization header {token}",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });

AddSecurityDefinition – This method lets you define how your API is secured by defining one or more security schemes.

It lets you enable the below schemes. (One can use multiple security schemes too if needed.)

In the example, I have used ApiKeyscheme.

Token and header details are provided manually but can be obtained programmatically.

Usually, JWT bearer secured token can be made available as an environment variable or Secret Storage or could be made available through the DI using a configuration file or YML files.


AddSecurityRequirement – This method lets you control the given authentication scheme applied at either the Global level or Operation level.

 c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                {
                    { "Bearer", new string[] { } }
                });

  • Global Authentication scheme

In the above example, we have used a global authentication scheme, this scheme will be applied to all REST API within Controllers.

In AddSecurityRequirement() when applying schemes of type other than “oauth2”, the array of scopes MUST be empty.

  • Local Authentication scheme

This scheme will be applied at the API Operation level. Operation-specific security can be added by using Interface IOperationFilter. Please see Enable JWT authorization in Swagger at the Operation level.

The complete code for the ConfigureServices method is as below,

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "MyTestService", Version = "v1" });
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
                {
                    Description = "JWT Authorization header \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                {
                    { "Bearer", new string[] { } }
                });
            });
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme);
         
        }

Configure() method will remain as above.

Once you run API, the Authorize button will be visible in swagger UI.

blank

Please provide bearer value and click on Authorize. Bearer token can be generated using a simple process and is discussed in our last article on JWT Authentication in .NET Core.

JWT (JSON Web Token)

Here let’s use the Generated JWT token in the previous article which is as below,

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjIyNjQ4MTgsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0Mzc4IiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNzgifQ.
gNlEt2dgPOYHVgGLU2OxzLIuvkPQ6rOeO6_qziKOSl4

Let’s execute the API to validate the authentication and see if it is working fine.

blank

Bearer token part should be appended with ‘bearer’

Example: bearer [token]

That’s all, you are all set to use swagger with JWT authorization token. This authorization will be used for all swagger API which is attributed with [Authorize] attribute.

This token will be used for all secured API until its expiry.

blank

Response – Success ( 200)

After executing, please check the response as below, we receive a successful response status (200: Ok)

blank

Response – Unauthorized ( 401)

If the token value is invalid you would receive 401: Unauthorized error as below,

blank

If you are looking to understand how to customize Swagger API documentation pro-grammatically especially enabling the operation level authentication scheme, I would recommend you read the below few posts.


Summary

In this post, we learned how to add JWT bearer authorization to swagger documentation. Swagger or OpenAPI describes the standards and specifications for RESTFul API descriptions. In .NET Core it simple to enable an authentication scheme BasicAuthScheme, ApiKeyScheme, and OAuth2Scheme to API using the Swashbuckle Nuget package.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



11 thoughts on “Use JWT authorization token in swagger .NET Core

  1. Hi Thanks. Very helpful for me . I have requirement to populate key programmatically. Could you plz provide your inputs how to achieve that? Thanks.

  2. Hi-Thanks. Once you are authenticated to perform operation, will subsequent operation will use same auth keys or for every operation one needs to perform authorize ?

    1. Hello JM- Global configuration will not required you enter token for each operation. Once enabled same configuration can be used for each API untill token is valid.Thanks for your query.

    1. Hello Marsh , For .Net core 2.2.1 above you need minimum VS 2019. Thanks for reading and your question

Leave a Reply

Your email address will not be published. Required fields are marked *