Code2night
  • Home
  • Guest Posts
  • Tutorial
  • Languages
    • Angular
    • C
    • C#
    • HTML/CSS
    • Java
    • JavaScript
    • Node.js
    • Python
    • React
    • 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
  • Register
  • Login
  1. Home
  2. Blogpost

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

Date- Mar 04,2024

4499

Free Download Pay & Download

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 →

Comments

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 Join Us On Facebook
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
  • Blogs
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
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
By Language
  • Angular
  • C
  • C#
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • React
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page