Swashbuckle.aspnetcore: Basic authentication sample in test project

Created on 15 Nov 2016  路  3Comments  路  Source: domaindrivendev/Swashbuckle.AspNetCore

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.

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.

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

All 3 comments

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[] { } },});

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vanillajonathan picture vanillajonathan  路  3Comments

govin picture govin  路  3Comments

tibitoth picture tibitoth  路  3Comments

voroninp picture voroninp  路  3Comments

rgelb picture rgelb  路  3Comments