Authentication for swagger UI in production in ASP.Net Core 6.0 | Code2night.com
Code2night
  • Home
  • Blogs
  • Guest Posts
  • Tutorial
  • Post Blog
  • Register
  • Login
  1. Home
  2. Blogpost

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

Date- Mar 04,2024

4445

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.




Comments

Tags

Swagger UI
Swashbuckle
SwashbuckleAspNetCore
Rest API
Postman
Api Testing
ITextSharp
Export to Pdf
AspNet Core
AspNet
C#
View to Pdf in Aspnet
Scheduler
Fibonacci series in Java
Display Fibonacci Series
First C# Program
What is C?
C
C Programming
CodeLobster
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

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Panipat
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2026 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Terms & Conditions
  • Refund Policy
  • About Us
  • Privacy Policy
  • Json Beautifier
  • Guest Posts