Secure swagger docs page with username and password Asp Net Core 2.1

Joshua Leigh picture Joshua Leigh · Jul 15, 2018 · Viewed 8.3k times · Source

I am using Asp.Net Core 2.1 Web Api with Swashbuckle.aspnetcore.swagger

I want to secure api documentation page with username and password before granting access.

Sample documention page enter image description here

To make sure its not accessible by the public

Answer

Shaul Behr picture Shaul Behr · Feb 27, 2019

Copied from mguinness's answer on Github:


In .NET Core you use middleware, instead of a DelegatingHandler:

public class SwaggerAuthorizedMiddleware
{
    private readonly RequestDelegate _next;

    public SwaggerAuthorizedMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Path.StartsWithSegments("/swagger")
            && !context.User.Identity.IsAuthenticated)
        {
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            return;
        }

        await _next.Invoke(context);
    }
}

You will also need an extension method to help adding to pipeline:

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

Then add to Configure method in Startup.cs just before using Swagger:

app.UseSwaggerAuthorized();
app.UseSwagger();
app.UseSwaggerUi();

There's also a variant solution posted there how to do it with basic auth.