Please could someone create a working sample using Basic authentication (documentation and swagger UI)?
Doing a search gives a lot of conflicting samples, none of which seem to work with the .NET Core project.
See below configuration and accompanying Document Filter to enable Basic auth for all operations. If you need to assign more granular security requirements then use an Operation Filter instead.
// Startup.cs
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new Info
{
Version = "v1",
Title = "Swashbuckle Sample API"
}
);
c.AddSecurityDefinition("basic", new BasicAuthScheme { Type = "basic" });
c.DocumentFilter<BasicAuthDocumentFilter>();
});
// BasicAuthDocumentFilter.cs
{
public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
{
var securityRequirements = new Dictionary<string, IEnumerable<string>>()
{
{ "basic", new string[] { } } // in swagger you specify empty list unless using OAuth2 scopes
};
swaggerDoc.Security = new[] { securityRequirements };
}
}
@domaindrivendev u rocks!
this also works:
c.AddSecurityDefinition("basic", new BasicAuthScheme {Type = "basic", Description = "basic authentication" });
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> {
{ "basic", new string[] { } },});
Most helpful comment
See below configuration and accompanying Document Filter to enable Basic auth for all operations. If you need to assign more granular security requirements then use an Operation Filter instead.