.NET -Swagger Web API for Basic Authentication

In case of Web API with Basic authentication. We have to pass the user credentials in HTTP request header.

By default swagger ui does not  have text boxes to pass the header values. But by virtue of the extensible features of swashbuckle – IOperationFilter class we can have the authorization Header input value text box in ui.

Steps to include authorization header in swagger ui.

  1. Add a class AddRequiredHeaderParameter and inherit from IOperationFilter     class AddRequiredHeaderParameter IOperationFilter
  2. Implement method Apply like below, Note the @in vlaue
    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
                });
     
                operation.parameters.Add(new Parameter
                {
                    name = "api-version",
                    @in = "query",
                    type = "string",
                    description = "API Version ",
                    required = true
                });
            }

Here we have extended the Operation with two value input i.e.

Authorization – of type header, For passing the Encoded User details. like, Basic xxxxxxxxxxxxxxx.

Api-version –  of default type “query”, Supports for api versioning takes input values like 1.0/1.1

3. Next we have to include the register/include the above new class(AddRequiredHeaderParameter ) in swagger Globalconfiguration.

    c.OperationFilter<AddRequiredHeaderParameter>();
 
})
    .EnableSwaggerUi(c =>
        {

 

After change swagger screenshot:

swag

3 thoughts on “.NET -Swagger Web API for Basic Authentication

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s