Let us put the keywords up front: Swashbuckle Basic authentication setup that works for Swashbuckle.WebApi installed on WebAPI projects (.NET 4.x). It’s also much less common to need Basic auth nowadays where proper mechanisms are easily available in all shapes and sizes. However, it may just become useful for internal tools or existing integrations.
Why?
Most tutorials online would cover the next gen library aimed specifically at ASP.Net Core, which is great (we’re all in for tech advancement), but sometimes legacy needs a prop up. If you are looking to add Basic Auth to ASP.NET Core project – look up AddSecurityDefinition
and go from there. If legacy is indeed the in trouble – read on.
Setting it up
The prescribed solution is two steps:
1. add authentication scheme on SwaggerDocsConfig
class
2. attach authentication to endpoints as required with IDocumentFilter
or IOperationFilter
Assuming the installer left us with App_Start/SwaggerConfig.cs
file, we’d arrive at:
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
...
c.BasicAuth("basic").Description("Basic HTTP Authentication");
c.OperationFilter<BasicAuthOpFilter>();
...
});
}
}
and the most basic IOperationFilter
would look like so:
public class BasicAuthOpFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
operation.security = operation.security ?? new List<IDictionary<string, IEnumerable<string>>>();
operation.security.Add(new Dictionary<string, IEnumerable<string>>()
{
{ "basic", new List<string>() }
});
}
}