Enable Authorization header in swagger


Story by Abhilash on Web API

Share   

It's quite normal that if you are creating APIs you will be using Swagger for previewing and testing your APIs. By default Swagger lists all your APIs with it's default values - request parameters, request method and response. That's quite handy.

Now, assume that you enabled bearer token for your API. How you'll show that in Swagger preview? Here is how you could do that. 

using Swashbuckle.Swagger;

public class IncludeAuthoriseHeaderParameter : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var filterPipeline = apiDescription.ActionDescriptor;

        // check whether API can be accessed anonymously
        var attrib = filterPipeline.GetCustomAttributes<AllowAnonymousAttribute>();

        // API is not anonymous
        if (!attrib.Any())
        {
            // check whether API has any query strings, if not instantiate
            if (operation.parameters == null)
            {
                operation.parameters = new List<Parameter>();
            }

            operation.parameters.Add(new Parameter
            {
                name = "Authorization",
                @in = "header",
                @default = "Bearer add-your-token-here",
                type = "string",
                required = true,
                description = "Bearer token"
            });
        }
    }
}

 Now, add this OperationFilter in your SwaggerConfig.cs file. 

GlobalConfiguration.Configuration.EnableSwagger(c=>
{ 
    // ...
    // ...
    // ...

    c.OperationFilter<IncludeAuthoriseHeaderParameter>(); 

    // ...
    // ...
    // ...
});

 Hope this helps.

 

 








comments powered by Disqus

Related Story   →

There is already an open DataReader associated with this Command which must be closed first

Last week, I deployed one of the Web API website that uses Entity Framework to production server. In