Saturday, June 9, 2018

Add Authorization Header Textbox in Swagger UI for Web API Basic Authentication

I wanted to test the Web API methods using Swagger UI. The Web API has Basic authentication enabled. For each request I need to pass the username and password in the format of base64 encoded. But by default the Swagger UI doesn't have any textbox to accept Authorization credentials parameters. To enable it I had to use the below code in SwaggerConfig.cs file. It should be available inside project's App_Start folder.
internal class AddRequiredHeaderParameter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
operation.parameters = new List<Parameter>();

operation.parameters.Add(new Parameter
{
name = "Authorization",
@in = "header",
type = "string",
description = "Authorization Header",
required = true
});
}
}
Then add the below code inside the ConfigureSwagger(SwaggerDocsConfig config) method to register it.
private static void ConfigureSwagger(SwaggerDocsConfig config)
{
// existing code
// ...
// ...
config.OperationFilter<AddRequiredHeaderParameter>();
}