Swagger UI: pass custom Authorization header

fikkatra picture fikkatra · Aug 11, 2016 · Viewed 16k times · Source

I'm using Swashbuckle and Swagger on an ASP.NET Web API. I'm trying to find a way to pass an Authorization header containing a Bearer token through Swagger UI. I've been searching around, but all the answers seem to point at this link.

However, this assumes that the content of the header is known upfront. I really need a way to change the header within Swagger UI (right before hitting the 'Try it out!' button), because the Bearer token expires every hour. Something similar to the way Postman allows you to add headers.

It seems like such a ridiculously simple problem, but what is the answer?

Answer

Philippe De Croock picture Philippe De Croock · Aug 12, 2016

We ran into the same problem on our project. I also wanted to add the header parameters to the Swagger UI website. This is how we did it:

1. Define an OperationFilter class OperationFilters are executed on every API operation every time you build Swagger. According to your code, operations will be checked according to your filters. In this example, we make the header parameter required on every operation, but make it optional on operations that have the AllowAnonymous attribute.

    public class AddAuthorizationHeader : IOperationFilter
    {
        /// <summary>
        /// Adds an authorization header to the given operation in Swagger.
        /// </summary>
        /// <param name="operation">The Swashbuckle operation.</param>
        /// <param name="schemaRegistry">The Swashbuckle schema registry.</param>
        /// <param name="apiDescription">The Swashbuckle api description.</param>
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {
            if (operation == null) return;

            if (operation.parameters == null)
            {
                operation.parameters = new List<Parameter>();
            }

            var parameter = new Parameter
            {
                description = "The authorization token",
                @in = "header",
                name = "Authorization",
                required = true,
                type = "string"
            };

            if (apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any())
            {
                parameter.required = false;
            }

            operation.parameters.Add(parameter);
        }
    }

2. Tell Swagger to use this OperationFilter In the SwaggerConfig, just add that the operation filter should be used as follows:

    c.OperationFilter<AddAuthorizationHeader>();

Hope this helps you out!