Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet HTML/CSS Java JavaScript Node.js Python Python 3.11, Pandas, SQL
      Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. 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 Updated Mar 2026 4538 Free Download Pay & Download
asp net core swagger ui

Understanding Swagger UI and Its Importance

Swagger UI is a powerful tool that provides an interactive interface for API documentation. It allows developers and users to visualize and interact with the API's endpoints without needing to write any code. However, exposing this interface publicly can lead to security vulnerabilities, especially if sensitive data is involved. By implementing authentication, you can control access to the Swagger UI, ensuring that only authorized personnel can view or interact with your API documentation.

In a production environment, securing your API documentation is not just a best practice; it is essential. Unauthorized access can lead to data breaches, misuse of API functionality, and other security issues. Therefore, implementing authentication is critical in protecting your application's integrity and user data.

Prerequisites

Before you begin, ensure you have the following prerequisites:

  • Basic understanding of ASP.NET Core and C#.
  • ASP.NET Core 6.0 SDK installed on your machine.
  • A working ASP.NET Core application where you want to implement Swagger UI authentication.

Implementing Basic Authentication for Swagger UI

To secure your Swagger UI, you will create a custom middleware that checks for basic authentication credentials in the request headers. Here's how to set it up:

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); } } }

The above middleware checks if the request path starts with '/swagger'. If it does, it inspects the 'Authorization' header for basic authentication credentials. If the credentials are valid, it allows the request to proceed; otherwise, it responds with a 401 Unauthorized status.

Registering the Middleware in Program.cs

Next, you need to register the authentication middleware in your application's startup configuration. Open your Program.cs file and add the necessary code:

var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); 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();

Make sure to call UseSwaggerAuthorized() before UseSwagger() and UseSwaggerUI() to ensure that the authentication middleware is executed before accessing the Swagger UI.

Testing Your Swagger UI Authentication

After implementing the middleware and updating your Program.cs file, run your application. When you navigate to the Swagger UI, you should see a prompt for credentials. Enter the username and password you defined in your middleware (in this case, 'Swagger' and 'Shubham123') to access the API documentation.

Here's what you can expect:

Authentication for swagger UI in production in ASPNet Core 60

If the credentials are correct, you will be granted access to the Swagger UI. If not, you'll receive a 401 Unauthorized response.

Edge Cases & Gotchas

While implementing basic authentication for Swagger UI, consider the following edge cases and gotchas:

  • Invalid Credentials: Ensure that invalid credentials return a clear 401 response to prevent confusion.
  • Session Management: Basic authentication does not maintain session state. Users will need to re-enter credentials if they navigate away from the Swagger UI.
  • HTTPS Requirement: Always use HTTPS when transmitting credentials to prevent interception during transmission.

Performance & Best Practices

When securing your Swagger UI, consider the following best practices:

  • Use Strong Passwords: Ensure that the credentials used for authentication are strong and not easily guessable.
  • Monitor Access: Implement logging to monitor access attempts to your Swagger UI. This can help identify unauthorized access attempts.
  • Limit Access: If possible, restrict access to the Swagger UI to specific IP addresses or use VPNs to limit exposure.
  • Regularly Update Credentials: Change your authentication credentials periodically to improve security.

Conclusion

Securing your Swagger UI in a production environment is vital for protecting your API documentation and sensitive information. By implementing basic authentication, you can control access and ensure that only authorized users can view your API endpoints. Here are the key takeaways:

  • Implement basic authentication to secure your Swagger UI.
  • Always use HTTPS to protect credentials during transmission.
  • Monitor access and regularly update authentication credentials.
  • Consider additional security measures such as IP whitelisting and logging.
Authentication for swagger UI in production in ASPNet Core 60 2

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

Related Articles

Best Practices for Securing Grok API Integrations in ASP.NET
Apr 04, 2026
How to Integrate Google Sign in Asp.net Core 8.0
May 05, 2024
Owin Authentication in Asp.net MVC Api
Oct 13, 2022
Integrating ASP.NET Core Identity with NHibernate for Robust User Management
Apr 06, 2026
Previous in ASP.NET Core
Integrating Google Translate into ASP.NET Webpage
Next in ASP.NET Core
How to read json file in asp.net Core
Buy me a pizza

Comments

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26016 views
  • Exception Handling Asp.Net Core 20773 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20250 views
  • How to implement Paypal in Asp.Net Core 19640 views
  • Task Scheduler in Asp.Net core 17548 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 | 1770
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
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • HTML/CSS
  • Java
  • JavaScript
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor