Configuring Swashbuckle for EPiServer Service API Bearer token

If you use EPiServer Service API you will probably also use Swashbuckle. Swashbuckle will generate a swagger (OpenAPI) specification and a handy-dandy UI for your Web APIs, as such for the Service APIs too.

One thing that annoys me is that I can't test the the Service APIs in the swagger UI because I need to supply a bearer token in the Authentication header and the Swashbuckle won't let me. Swashbuckle supports Basic Auth, ApiKey and OAuth2.0 but none of them allows us to key in a bearer token straight into the Authorization header.

We can fix this by telling Swashbuckle to add a field called "Authorization" for the Authorization header of the request:

public class AddAuthorizationHeaderParameterOperationFilter: IOperationFilter
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
        var isAuthorized = filterPipeline
                               .Select(filterInfo => filterInfo.Instance)
                               .Any(filter => filter is IAuthorizationFilter);

       var allowAnonymous = apiDescription.ActionDescriptor

       if (isAuthorized && !allowAnonymous)
           operation.parameters.Add(new Parameter {
               name = "Authorization",
               @in = "header",
               description = "Bearer token (e.g. BEARER enterbearertokenhere)",
               required = true,
               type = "string"                    

Source: GitHub, by jskepnek.

And then configuring it with Swashbuckle in the SwaggerConfig class

    .EnableSwagger(c =>
            c.SingleApiVersion("v1", "api");
    .EnableSwaggerUi(c => { });

Start EPiServer and see that the Authorization header appeared for all the restricted Service APIs. Note that you need to put BEARER in front of your token when filling in the Authorization field.