Tuesday, March 6, 2018

How to add Authorization Header (Custom Header) in Swagger UI

In this blog, we are going to discuss how to add custom header parameter (authorization header) in Swagger UI for ASP.Net web API.

We use request header (like authentication) to pass client information to web API but in Swagger UI, there is no any simple or straight way to add custom header parameter.
To add customer header parameter in Swagger UI, we need to implement IOperationFilter interface

internal class AuthorizationHeaderParameterOperationFilter : 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 = "X-API-Token",
                @in = "header",
                description = "access token",
                required = true,
                type = "string"
            });
        }
    }

SwaggerConfig .cs :

public static void Register()
        {
            var thisAssembly = typeof(SwaggerConfig).Assembly;
            GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                {
                    c.SingleApiVersion("v1""DemoWebAPI");
                    c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
                })
                .EnableSwaggerUi(c => { });
        }


As below you can see, X-API-token as additional parameter for your Web API to take authorization token and pass to web API for user authentication 

Swagger UI Add Authorization Header (Custom Header)
Swagger UI Add Authorization Header (Custom Header)



Other swagger related posts:
·         Disable Swagger UI


Thanks for visiting!!

2 comments:

Unknown said...

Is there any way to do this without displaying header input fields in the UI?

I am having a great deal of trouble finding a way to add custom header fields with static, preset values to all swagger API calls, without displaying the fields and their values in the UI.

Nitesh said...


I tried this. The customer header comes under Results View of httpContext.Request.Headers resultset but when I do var key = httpContext.Request.Headers.Where(z => z.Key == "CUSTOMKEY").FirstOrDefault(); I get key as [null,null]. Any ideas?

SQL Server - Identify unused indexes

 In this blog, we learn about the index usage information (SYS.DM_DB_INDEX_USAGE_STATS) and analyze the index usage data (USER_SEEKS, USER_S...