Login Register
Code2night
  • Home
  • Guest Posts
  • Blog Archive
  • Tutorial
  • Languages
    • Angular
    • C
    • c#
    • C#
    • HTML/CSS
    • Java
    • JavaScript
    • Node.js
    • Python
    • React
    • Security
    • SQL Server
    • TypeScript
  • Post Blog
  • Tools
    • JSON Beautifier
    • HTML Beautifier
    • XML Beautifier
    • CSS Beautifier
    • JS Beautifier
    • PDF Editor
    • Word Counter
    • Base64 Encode/Decode
    • Diff Checker
    • JSON to CSV
    • Password Generator
    • SEO Analyzer
  1. Home
  2. Blog
  3. Authentication for swagger UI in production in ASP.Net Core 6.0

Authentication for swagger UI in production in ASP.Net Core 6.0

Date- Mar 04,2024

4506

Free Download Pay & Download
asp net core swagger ui

Add a new class called SwaggerBasicAuth and add the following code.

    public class SwaggerBasicAuth
    {
        private readonly RequestDelegate next;
        public SwaggerBasicAuth(RequestDelegate next)
        {
            this.next = next;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            if (context.Request.Path.StartsWithSegments("/swagger"))
            {
                string authHeader = context.Request.Headers["Authorization"];
                if (authHeader != null && authHeader.StartsWith("Basic "))
                {
                    // Get the credentials from request header
                    var header = AuthenticationHeaderValue.Parse(authHeader);
                    var inBytes = Convert.FromBase64String(header.Parameter);
                    var credentials = Encoding.UTF8.GetString(inBytes).Split(':');
                    var username = credentials[0];
                    var password = credentials[1];
                    // validate credentials
                    if (username.Equals("Swagger") && password.Equals("Shubham123"))
                    {
                        await next.Invoke(context).ConfigureAwait(false);
                        return;
                    }
                }
                context.Response.Headers["WWW-Authenticate"] = "Basic";
                context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
            }
            else
            {
                await next.Invoke(context).ConfigureAwait(false);
            }
        }
    }

    public static class SwaggerExtensions
    {
        public static IApplicationBuilder UseSwaggerAuthorized(this IApplicationBuilder builder)
        {
            // Your middleware registration goes here
            return builder.UseMiddleware<SwaggerBasicAuth>();
        }
    }

Open the program.cs file and add the following code 

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "SwaggerAuth", Version = "v1" });
});


    app.UseSwaggerAuthorized();
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerAuth V1");
    });

Complete code of the program.cs

using SwaggerAuth;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo { Title = "SwaggerAuth", Version = "v1" });
});


var app = builder.Build();

// Configure the HTTP request pipeline.

 app.UseSwaggerAuthorized();
app.UseSwagger();
app.UseSwaggerUI(c =>
  {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "SwaggerAuth V1");
  });


app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
Ensure that UseSwaggerAuthorized() is added before the calls to UseSwagger() and UseSwaggerUI(), so that the authentication middleware is invoked prior to accessing the Swagger UI. Press F5 to run. You will notice that the Swagger page is loading, but the browser is prompting for credentials.




S
Shubham Batra
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

How to Integrate Google Sign in Asp.net Core 8.0
May 05, 2024
Owin Authentication in Asp.net MVC Api
Oct 13, 2022
Understanding Middleware in ASP.NET Core: A Comprehensive Guide
Mar 16, 2026
HTTP Error 500.32 Failed to load ASP NET Core runtime
Dec 06, 2023

Comments

Contents

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 25926 views
  • Exception Handling Asp.Net Core 20707 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20189 views
  • How to implement Paypal in Asp.Net Core 19601 views
  • Task Scheduler in Asp.Net core 17491 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1760
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Free Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Diff Checker
  • Base64 Encode/Decode
  • Word Counter
  • SEO Analyzer
By Language
  • Angular
  • C
  • c#
  • C#
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page