could anyone know how could i integrate basic auth with swashbuckle api's documentation?
I saw that there's a basicAuth function in the swaggerconfig file:
c.BasicAuth("basic").Description("Basic HTTP Authentication");
What i've done:
does anyone have any idea what did i miss?
Thanks!
A minor improvement on @MarwaAhmad 's most excellent answer, is to check for null parameters (e.g. a simple GET or call with all params in the URL) . Also added details for Basic Auth.
Also, if you already use a global IAuthorizationFilter
for say enforcing HTTPS, then you will want to change the more general
filter => filter is IAuthorizationFilter
to a specific
filter => filter is AuthorizeAttribute
public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Instance)
.Any(filter => filter is IAuthorizationFilter);
var allowAnonymous =
apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAuthorized && !allowAnonymous)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();
operation.parameters?.Add(new Parameter
{
name = "Authorization",
@in = "header",
description = "Basic HTTP Base64 encoded Header Authorization",
required = true,
type = "string"
});
}
}
}
Here's how i did httpbasic authentication:
public class AddAuthorizationHeaderParameterOperationFilter: IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
var isAuthorized = filterPipeline
.Select(filterInfo => filterInfo.Instance)
.Any(filter => filter is IAuthorizationFilter);
var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
if (isAuthorized && !allowAnonymous)
{
operation.parameters.Add(new Parameter {
name = "Authorization",
@in = "header",
description = "access token",
required = true,
type = "string"
});
}
}
}
The api's user shall write in the field value: basic [un:pw].tobase64.
References: swashbuckle's issue 326 swashbuckle issue 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With