Swagger UI: pass custom Authorization header

You could do it in different ways depending on how you collect the Authorization header and whether you want the code to handle everything or if you want the user to be able to enter what ever Authorization header they want.

When I first tried this, I was able to show an Authorization header text in each endpoint's parameter field area where a user could type in an Authorization header but that was not what I wanted.

In my situation, I had to send a request to the /token endpoint with the user's cookie in order to get a valid Authorization token. So I did a mix of things to achieve this.

First in SwaggerConfig.cs I uncommented c.BasicAuth() to get the basic auth scheme into the API schema and I also injected a custom index.html page where I inserted an AJAX request in order to grab the Authorization token, using the user's cookie (index.html code shown below):

public static void Register() {

    System.Reflection.Assembly thisAssembly = typeof(SwaggerConfig).Assembly;

    System.Web.Http.GlobalConfiguration.Configuration
                .EnableSwagger(c => {
                    ...

                    c.BasicAuth("basic").Description("Bearer Token Authentication");

                    ...
                })
                .EnableSwaggerUi(c => {
                    ...

                    c.CustomAsset("index", thisAssembly, "YourNamespace.index.html");

                    ...
                });
}

Then head here to download the swashbuckle index.html which we will customize to insert an Authorization header.

Below I simply make an AJAX call to my /token endpoint with a valid cookie, get the Authorization token, and give it to swagger to use with window.swaggerUi.api.clientAuthorizations.add():

...

function log() {
  if ('console' in window) {
    console.log.apply(console, arguments);
  }
}

$.ajax({
    url: url + 'token'
  , type: 'POST'
  , data: { 'grant_type': 'CustomCookie' }
  , contentType: 'application/x-www-form-urlencoded'
  , async: true
  , timeout: 60000
  , cache: false
  , success: function(response) {
        console.log('Token: ' + response['token_type'] + ' ' + response['access_token']);
        window.swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", response['token_type'] + ' ' + response['access_token'], "header"));
    }
  , error: function(request, status, error) {
        console.log('Status: ' + status + '. Error: ' + error + '.');
    }
});

I removed a few things from the AJAX call to make it more simple and obviously your implementation will probably be different depending on how you gather your Authorization token and stuff but that gives you an idea. If you have any specific issues or questions, let me know.

*Edit: Did not notice you actually did want the user to type in their Authorization header. In that case it is very easy. I used this post. Simply created the following class to do the work:

public 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 = "Foo-Header",
            @in = "header",
            type = "string",
            required = true
        });
    }
}

Then added the class to my SwaggerConfig like so:

...
c.OperationFilter<AddRequiredHeaderParameter>();
...

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!


Create a new operation filter that implements IOperationFilter.

public class AuthorizationHeaderOperationFilter : IOperationFilter
{
    /// <summary>
    /// Adds an authorization header to the given operation in Swagger.
    /// </summary>
    /// <param name="operation">The Swashbuckle operation.</param>
    /// <param name="context">The Swashbuckle operation filter context.</param>
    public void Apply(Operation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
        {
            operation.Parameters = new List<IParameter>();
        }

        var authorizeAttributes = context.ApiDescription
            .ControllerAttributes()
            .Union(context.ApiDescription.ActionAttributes())
            .OfType<AuthorizeAttribute>();
        var allowAnonymousAttributes = context.ApiDescription.ActionAttributes().OfType<AllowAnonymousAttribute>();

        if (!authorizeAttributes.Any() && !allowAnonymousAttributes.Any())
        {
            return;
        }

        var parameter = new NonBodyParameter
        {
            Name = "Authorization",
            In = "header",
            Description = "The bearer token",
            Required = true,
            Type = "string"
        };

        operation.Parameters.Add(parameter);
    }
}

Configure the service in your Startup.cs file.

        services.ConfigureSwaggerGen(options =>
        {
            options.OperationFilter<AuthorizationHeaderOperationFilter>();
        });