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
blank

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/

blank

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.

blank

Please provide username and password value and click on Authorize.

blank

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.

blank

After executing, please check the response,

blank

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.



19 thoughts on “Use Basic Authentication in Swagger ASP.NET Core

  1. How does the authentication work? I have custom authenticationhandlers in my asp.net core web api and none of them gets triggered when I press on “login”.

    1. Hello Florent – User name and password provided in the swagger UI will be used to create an auth header i.e Authorization: Basic . This will be sent to Controller(Route) enabled with Authorize attribute which in turn will be validated using AuthenticationHandlers as per middleware configured in API pipeline.

      Kindly visit the article on setting up Basic Authentication in ASP.NET Core

      1. It is very weird. When I send my api calls via postman the authenticationhandlers get triggered as expected. When I do it thorugh SwaggerUI they dont get triggered. I am using exactly that code of the side which you are providing.

      2. Hi Florent – Thanks for more details. May I know which .NET Core version and Swagger version(V2 or V3) you are using? Based on the answer I can try helping you to fix the issue.

  2. I have followed the steps outlined above.
    I have a few issues.
    When adding the code to ConfigureServcies – I get a compile error.
    services.AddSwaggerGen(
    {
    c.SwaggerDoc(“v1”, new Info { Title = “MyTestService”, Version = “v1” });
    });
    “The name ‘c’ does not exist…”

    Should this be
    services.AddSwaggerGen(c =>
    {
    c.SwaggerDoc(“v1”, new Info { Title = “MyTestService”, Version = “v1” });
    });

    Also when adding code to Configure

    app.UseSwaggerUI(
    {
    c.SwaggerEndpoint(“/swagger/v1/swagger.json”, “TestService”);
    });
    Should this be
    app.UseSwaggerUI(c =>
    {
    c.SwaggerEndpoint(“/swagger/v1/swagger.json”, “TestService”);
    });

    When I run this with the changes I have made I get a blank page with this text
    https://localhost:5001/api/values
    {“value1″,”value2”}

    Please help

      1. You may want to mention that in
        ConfigureServices()
        services.AddOptions(); is required

      2. Hey Richard- Thanks for your query. I have removed it.

        AddOptions is required if you need to access Key-Value pair from configuration and wants to do DI in other components using IOption interface mainly used typesafe configuration.
        I had that in the original app but it is not needed for enabling basic auth specifically.
        Thanks.

  3. I am using Asp.net core 2.2 but when I declaring AddSecurityDefinition BasicAuthScheme is missing is not available.

    Below is my code please correct me if I am missing something or going wrong anywhere.

    [cc lang=”C#”]c.AddSecurityDefinition(“basic”, new BasicAuthScheme
    {
    Type = “basic”,
    Description = “basic authentication for API”
    });
    c.AddSecurityRequirement(new Dictionary<string, IEnumerable>
    {
    { “basic”, new string[] { } }
    });[/cc]

    1. Hi Mahavirsinh – Thanks for the query. Please make sure to install Swashbuckle.AspNetCore which in turn installs Swashbuckle.AspNetCore.Swagger where the BasicAuthScheme will be available.

  4. I’ve added both Basic and Bearer authorization to my API:

    [cc lang=”c#”]c.AddSecurityDefinition(“Basic”, new BasicAuthScheme
    {
    Type = “basic”,
    Description = “Enter a username and password”
    });

    c.AddSecurityRequirement(new Dictionary<string, IEnumerable>
    {
    { “basic”, new string[] { } }
    });

    c.AddSecurityDefinition(“Bearer”, new ApiKeyScheme
    {
    Name = “Authorization”,
    In = “header”,
    Type = “apiKey”,
    Description = “Enter a session token”
    });[/cc]

    and configured the Basic through the Swagger page but when I send a request the Authorization header isn’t being added. Have I missed something?

      1. Hey Craig, Thanks for your query. I see in your code below code is missing,
        [cc] c.AddSecurityRequirement(new Dictionary>
        {
        { “Bearer”, new string[] { } }
        });[/cc]
        We need to add Security requirments for each security scheme. Here i beleive you are looking for Global security declaration.
        If you need to define operation-specific security scheme please refer this article JWT authorization in swagger using OperationFilter in .NET Core
        However, glad that the issue is resolved!

  5. Hi, the article is really helpful, but when I follow it visual studio can’t find the BasicAuthScheme, what namespace is it in?

    1. Thanks Alistair for your comments. Appreciate that.

      If you are using .NET Core 2.2 then this namespace will be available directly in the “Swashbuckle.AspNetCore.Swagger”.

      For .NET Core 3.0 + all security schemes are moved to “Microsoft.OpenApi.Models”.Please refer this link for 3.0 support – ASP.NET Core 3.0 – Basic Authentication in Swagger (Open API)
      Please do let me know if you still have an issue. I shall be happy to help you.

Leave a Reply

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