JWT bearer Authorization in Swagger OpenAPI

Use JWT Bearer Authorization Token in Swagger OpenAPI

In this article, we will learn – how to enable JWT bearer Authorization in Swagger OpenAPI definition in API projects to execute various operations via swagger UI.

Today in this article we will cover below,

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

In our last article, we learned how to Enable Swagger/Open API documentation to ASP.NET Core API in simple 2-3 steps.

We also learned JWT Authentication in ASP.NET Core 3.1 or .NET 5.0 with examples in our last article.

JWT Authorization Token in Swagger

Please kindly see the below article to understand the basic 2-3 steps workflow for enabling swagger in ASP.NET Core 3.1 or .NET 5 or .NET 6

Please add two below methods as shown below,

  • AddSecurityDefinition()

  • AddSecurityRequirement()

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

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

  • JWT Bearer token using ApiKeyScheme

Please make a note that there are a few breaking changes introduced in the recent ASP.NET Core 3.1 Swagger supports if you are migrating from older version.

A few major breaking changes for swagger in ASP.NET Core 3.1 and above are listed below,

  • Info class renamed OpenApiInfo

  • ApiKeyScheme class renamed to OpenApiSecurityScheme

  • AddSecurityRequirement method has been updated to take OpenApiSecurityRequirement as an object parameter etc.

Getting started

You need the below Nuget package of Swashbuckle to work with ASP.NET Core.

 PM> Install-Package Swashbuckle.AspNetCore -Version 5.0.1 

Please use the latest available version of ‘Swashbuckle.AspNetCore‘ as and when available.

Step 1

The addSecurityDefinition method is defined as below,

c.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.Http,
                    Scheme = "bearer",
                    BearerFormat = "JWT",
                    In = ParameterLocation.Header,
                    Description = "JWT Authorization header using the Bearer scheme."
                });

In the above example, I have used the ‘Bearer’ scheme with scheme type as ApiKey.

Usually, the 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.

Step 2

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

Please add the below code for AddSecurityRequirement()

c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                          new OpenApiSecurityScheme
                            {
                                Reference = new OpenApiReference 
                                { 
                                    Type = ReferenceType.SecurityScheme, 
                                    Id = "bearerAuth" 
                                }
                            },
                            new string[] {}
                    }
                });

Finally, the complete code for the ConfigureServices method is as below,

Configure() method will remain as above,

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseSwagger();

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

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors(x => x
               .AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader());

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

Authorize button will be enabled in the swagger UI as below.

The security scheme configured here will be used by all routes decorated with Authorize attributes as this is enabled at the global level.


AddSecurityRequirement swagger open API

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.eyJleHAiOjE1NzA5MDk3MDMsImlzcyI6Imh0dHBzOi8vbG9jYWxob3N0OjQ0MzQxIiwiYXVkIjoiaHR0cHM6Ly9sb2NhbGhvc3Q6NDQzNDEifQ.Is7QtMiknbSYHq8MFryCfXW25C8oK9tFZlD2jHEQTuo

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

AddSecurityDefinition swagger openapi

When using an HTTP Authentication scheme,

Note : If using SecuritySchemeType.ApiKey – token part should be appended with ‘bearer’.

Example: Bearer [token]

Note – If using SecuritySchemeType.Http – token need to be used without “bearer”

This authorization will be used for all swagger APIs that are attributed with the [Authorize] attribute due to the global settings defined above.

This token will be used for all secured APIs until it’s valid.

Response – Success ( 200)

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

We can see API decorated with [Authorize] keyword gets executed successfully from UI directly.

authorization bearer token in a swagger openapi

authorization bearer token in a swagger

Response – Unauthorized ( 401)

If the token value is invalid or expired – You would receive 401: Unauthorized error as below,

authorization bearer token openapi swagger

Understanding Global Vs Operation level scheme

  • Global Authentication scheme

Above we have used a global authentication scheme, this scheme will be applied to all REST APIs within Controllers and can be executed on all APIs decorated with the [Authorize] attribute.

In AddSecurityRequirement() the array of scopes MUST be empty I.e new string[] {} for JWT authorization.

  • Operation-level Authentication scheme

Please see Enable JWT authorization in Swagger at the Operation level on how to enable the JWT authorization scheme at a specific operation level.

That’s all!

Other references :

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

Summary

In this post, we learned new breaking changes with improved Swagger/ Open API document implementation.

We also learned, how to add JWT bearer authorization to Swagger documentation. Swagger or OpenAPI describes the standards and specifications of RESTFul API documentation.

It also helps to provide specifications around enabling authentication schemes BasicAuthScheme, ApiKeyScheme, and OAuth2Scheme to API using the Swashbuckle or NSwag tooling.



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.



16 thoughts on “JWT bearer Authorization in Swagger OpenAPI

  1. Great overview, thank you very much! I have my controller actions protected with Authorize Attributes (see below for an example). How can I get the required Roles displayed in the generated documentation for the action? Thank you in advance for any guidance!

    [ApiController]
    public class MyController : ControllerBase
    {
    [HttpGet]
    [Authorize(Roles = “admin”)]
    public IEnumerable Get()
    {

    }
    }

      1. Thank you for the suggestion. I’ll take at IOperationFilter – it looks like I can use that to inject custom documentation. The required role comes through on the Open API Spec, so I know it’s in there – I was just surprised that there isn’t anything out of the box to display the required Roles for a particular API.

  2. Just what I wanted to do, well explained and concise. Definitively a usefull article. Great!! 😉

Leave a Reply

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