Swagger In .NET

Authentication for swagger UI in production in ASP.Net Core

A Short guide on how to Secure your Swagger UI in production by providing proper authentication.

Nitesh Singhal
4 min readAug 4, 2021
Image By Nitesh Singhal

When you create a WebApi project with .NET 5 and above, you get swagger integrated out of box in the sample project.

Like this.

Webapi project using wizard in visual studio
Auto generated source code

As you can see in the picture developers has nicely added the swagger inside the development environment only. So you can see the swagger page in development mode only.

But what if you want to access the swagger page in production but at same time you also want that not everyone should be able to see the your api endpoints.

In this tutorial, I am going to explain how we can secure the swagger definition in production environment with some authentications mechanism.

In this tutorial, I am going to use basic authentication, so let’s start.

Create a webapi project with visual studio or VScode. I am using visual studio.

Let’s run the webapi by pressing F5 and see the swagger page by going to URL https://localhost:5001/swagger/index.html

Swagger page for webapi project

Now add a class called SwaggerBasicAuthMiddleware and add the following code.

public class SwaggerBasicAuthMiddleware
{
private readonly RequestDelegate next;
public SwaggerBasicAuthMiddleware(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("swagger"))
{
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);
}
}
}

For simplicity I am using hardcoded credentials but same can enhanced to use it from database also.

Create a extension method like this.

public static IApplicationBuilder UseSwaggerAuthorized(this IApplicationBuilder builder)
{
return builder.UseMiddleware<SwaggerBasicAuthMiddleware>();
}

Remove the swagger part from env.IsDevelopment() block and put it outside. Add the middleware in the startup.cs like below.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...app.UseAuthorization();app.UseSwaggerAuthorized();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "SecureSwagger v1"));
...}

Make sure that UseSwaggerAuthorized() is added before UseSwagger() and UseSwaggerUI() call, so that authentication middleware will be called before accessing swagger ui.

with these changes in code we are ready to run our application.

press F5 to run, you can see the swagger page is loading but browser is asking for credentials.

Swagger page asking for credentials

Let me first try with some invalid credentials. i will with ‘Test’ and ‘Test’ as username and password respectively.

Wrong Username and password

Once you press sign in button it will validate the credentials and return to same page if they are wrong.

if you press cancel, it wil show the 401 error page.

Now i will try with valid credentials.

and you can see the swagger is loaded successfully.

Swagger page showing successfully after validating credentials.

So what’s next…

you can enhance to use database for validating instead of hardcoded values.

swagger page can also be secure using OAuth and openidconnect, Read more about it. https://medium.com/@niteshsinghal85/securing-swagger-ui-in-production-in-asp-net-core-part-2-dc2ae0f03c73

Tell me your thoughts below!

If you liked this article please share the energy and press the clap button And follow me for more interesting articles like this one.

--

--

Nitesh Singhal

Software architect, Exploring ASP.Net core and containerization technologies