Use Basic Authentication in Swagger ASP.NET Core

Basic Authentication in Swagger

Swagger or OpenAPI describes the standards and specifications for the RESTFul API description. As we know these specifications are a great attempt to create a universal description for REST API.

Today in this article we will cover how to Use Basic Authentication in Swagger ASP.NET Core 2.2 and also ASP.NET Core 3.1 or the latest 6.0 version.

Today In this post, we will see how to add Basic Authentication to swagger documentation for .NET Core 2.2 and lower version.

Today in this article, we will cover below aspects,

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.

Swagger lets you define the different authentication types for an API,

If you are working on ASP.NET Core 3.1 or .NET 6

If interested to enable Basic Authentication in ASP.NET Core 3.1 or .NET 6, please see below article,

Getting started

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

Create a API sample service using NET Cor

Please add below Swashbuckle NuGet package to your WebAPI using a Command prompt or NuGet 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

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 =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Title = "MyTestService",
                    Version = "v1"
                });
             }
            services.AddTransient<IUserService, UserService>();
            services.AddAuthentication("BasicAuthentication").
            AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
        }

For enabling Basic Authentication in ASP.NET Core 2.2, please visit the below article,

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.

Please execute the swagger route,

https://localhost:44378/swagger/

Add Basic Authentication to Swagger

Please AddSecurityDefinition () and AddSecurityRequirement() methods as shown below.

AddSecurityDefinition – This method lets you define how your API is secured by defining one or more security schemes. It lets you enable the schemes like Basic Auth or JWT bearer or OAuth2 etc.. (Multiple security schemes can also be applied )

Final implementation of ConfigServices() method 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("basic", new BasicAuthScheme
                {
                    Type = "basic",
                    Description = "basic authentication for API"
                });
                c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                {
                    { "basic", new string[] { } }
                });
            });
            services.AddTransient<IUserService, UserService>();
            services.AddAuthentication("BasicAuthentication").
            AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
        }

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

  • 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 also be added by using Interface IOperationFilter.

Please see Enable JWT authorization in Swagger at the Operation level to understand how to use Operation filter in swagger.

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

Please provide username and password value and click on Authorize.

That’s all, you are all set to use swagger with a Basic authentication enabled. This authentication will be used for all API in the service as it’s global in nature.

After executing, please check the response,

If the credentials are invalid you should receive 401: Unauthorized error.

Note: Swagger uses already enabled BasicAuthenticationHandler( derived from AuthenticationHandler) to verify the basic authentication credentials.

Please visit for more details :

ASP.NET Core 5 – Basic Authentication in ASP.NET Core with example

ASP.NET Core 2.2 – ASP.NET Core – Basic Authentication with example

That’s all!

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 articles.

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 how to add Basic Authentication to swagger API documentation. Swagger or OpenAPI describes the standards and specifications for RESTFul API descriptions. In .NET Core, it’s pretty simple to enable an authentication scheme like 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.