Basic Authentication using OperationFilter in Swagger(OpenAPI) ASP.NET Core

Basic Authentication in Swagger

Today in this article, we shall discuss, how to enable Basic Authentication in Swagger (OpenAPI V3.0) documentation in ASP.NET Core 3.1 using IOperationFilter.

If you have Basic Auth security schemes that you only want to apply to specific operations, then using IOpertionFilter makes it simple to configure.

You can also apply Global BasicAuthScheme in ASP.NET Core using AddSecurityRequirement.

There are a few differences and design updates in OpenAPI or Swagger 3.0.

Today in this article, we will cover below aspects,

As we discussed in our last articles recently released Swagger 3.0 (OpenAPI v3.0 document specifications) documentation has brought a lot of improvements which include a few breaking changes too.

IOperationFilter also lets you define multiple security schemes if needed.

Getting Started

Create ASP.NET Core 3.1 or .NET 6 API

Please install below Nuget package below,

PM> Install-Package Swashbuckle.AspNetCore -Version 5.3.3

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

Please add below AddSecurityDefinition() methods to your swagger middleware.

We need to use the SecurityScheme type as “basic” and define the OpenAPI basic auth scheme as shown in the below implementation.

AddSecurityDefinition() methods let you define your API security by defining one or more security schemes like OAuth2 or JWT Bearer Scheme or Basic Authentication scheme.

 services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "TheCodeBuzz-Service", Version = "v1" });
                c.AddSecurityDefinition("basic", new OpenApiSecurityScheme
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.Http,
                    Scheme = "basic",
                    In = ParameterLocation.Header,
                    Description = "Basic Authorization header."
                });
                c.OperationFilter<AuthOperationFilter>();
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
           }

Implement IOperationFilter Interface

Above we have used the class AuthOperationFilter which is implemented for the Basic Auth scheme using the IOperationFilter.

Here class AuthOperationFilter will be derived from IOperationFilter and we have to override Apply (..) method as below.

 public class AuthOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var isAuthorized = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() ||
                context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any();
            if (!isAuthorized) return;
            operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" });
            operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" });
            var basicSecurityScheme = new OpenApiSecurityScheme()
            {
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "basic" },
            };
            operation.Security.Add(new OpenApiSecurityRequirement()
            {
                [basicSecurityScheme] = new string[] { } 
            });
        }
    }

Please, note that we can retrieve API descriptions for relevant information like attribute, route information, etc. using the IOperationFilter interface.

Please update the Configure() method as below,

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseHttpsRedirection();
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "TestService");
            });
   
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

The generated swagger definition will have the ‘Authorize’ button visible.

Once click on the button, it lets you enter Basic authentication credentials i.e. UserName and Password.

Based on OperationFilter logic this lock icon will be displayed only for specified APIs where criteria match.

Example– In the below example, we are validating the “Authorize” attribute for an operation to apply a given security scheme.

Our API has two GET methods and only one is secured with the [Authorize] attribute.

Basic Authentication using OperationFilter in SwaggerOpenAPI ASPNET Core

Please click on the Authorize Button and provide Basic Auth credentials.

Basic Authentication using OperationFilter in SwaggerOpenAPI ASPNET Core

200 Success (OK)

You shall receive 200 or relevant success codes for valid credentials.

Basic Authentication using OperationFilter in SwaggerOpenAPI ASPNET Core

401 UnAuthorized

You shall receive 401 failure codes for invalid credentials.

That’s all, you are all set to use Swagger with Basic Auth token using OperationFilter.

Other references :

Summary

In this post, we learned how to add the BasicAuth Authentication scheme to Swagger (OpenAPI) documentation in the ASP.NET Core application using OperationFilter techniques.



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.



2 thoughts on “Basic Authentication in Swagger (OpenAPI) using OperationFilter in ASP.NET Core

    1. Hi Thomas – Thank you for your query.
      Basic auth credentials passed through swagger will be validated against the Authentication scheme you have enabled within your API pipeline. Mostly you will have to enable that security as middleware or Handler or filter. You may use using Basic Auth, JWT bearer or OAuth2, etc)
      The good thing is Swagger gives us the ability to send credentials through headers(Ex. ‘Authorization’ header) or custom user name to validate secured calls etc.

Leave a Reply

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