Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass custom headers while calling a web api using Swagger(Swashbuckle)

We are using Swashbuckle to document our web apis and use it to test our web apis. I want to know how one can pass multiple custom headers with different values for each request using Swagger UI.

I have seen an answer like below in the internet to pass a header in Swagger UI but was unable to get my head around it. What's confusing is about the SwaggerExtensions file. What is the purpose of this file and why is there a mention of this file in the qualified name of the js file.

1.Add new file named “SwaggerExtensions”, then added new JS file named “onComplete.js”, you have to change the build action for this file to “Embedded Resource”.

2.Inside the file “onComplete.js” paste the following code:

$('#input_apiKey').change(function () {

var key = $('#input_apiKey')[0].value;
if (key && key.trim() != "") {
key = "Bearer " + key;
window.authorizations.add("key", new ApiKeyAuthorization("Authorization",   key, "header"));
}
});

3.Open file “SwaggerConfig.cs” and inside the register method paste the code below:

SwaggerUiConfig.Customize(c =>
{
 c.SupportHeaderParams = true;
 c.InjectJavaScript(typeof(SwaggerConfig).Assembly,        "AngularJSAuthentication.API.SwaggerExtensions.onComplete.js");
});
like image 302
Kiran R Avatar asked Jun 05 '15 14:06

Kiran R


Video Answer


2 Answers

Swashbuckles implementation of swagger reads XML code comments to generate the required swagger specification. Unfortunately, if you require an authorization header (access token) to make requests, the XML code comments does not provide this info to Swashbuckle. You'll have to manually inject this new parameter during swagger specification generation.

Swashbuckle provides an interface called IOperationFilter to apply new parameters. Implementing this interface will look something like this.

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.GetCustomAttributes<AllowAnonymousAttribute>().Any();

        if (isAuthorized && !allowAnonymous)
        {
            operation.parameters.Add(new Parameter {
                name = "Authorization",
                @in = "header",
                description = "access token",
                required = true,
                type = "string"                    
            });
        }
    }
}

Inside your SwaggerConfig.cs file, add the following

public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>


                c.SingleApiVersion("v1", "API").Description("An API ")
                                                        .TermsOfService("Some terms")
                                                        .Contact(cc => cc.Name("Team")
                                                        .Email("[email protected]"));

                c.OperationFilter(() => new AuthorizationHeaderParameterOperationFilter()));


      }
 }
like image 83
snimakom Avatar answered Sep 28 '22 10:09

snimakom


Swashbuckle suggest to use InjectJavaScript to accomplish this. https://github.com/domaindrivendev/Swashbuckle#injectjavascript

I use the following code to add a bearer token for authorization in http header.

httpConfiguration
.EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API")) co
.EnableSwaggerUi(c =>
    {
        c.InjectJavaScript(containingAssembly, "ProjectName.SwaggerUIEnableBearerToken.js");
    });

SwaggerUIEnableBearerToken.js

$(function () {
$('#input_apiKey').attr("placeholder", "bearer token");
$('#input_apiKey').off();
$('#input_apiKey').change(function () {
    var token = this.value;
    if (token && token.trim() !== '') {
        token = 'Bearer ' + token;
        var apiKeyAuth = new window.SwaggerClient.ApiKeyAuthorization("Authorization", token, "header");
        window.swaggerUi.api.clientAuthorizations.add("token", apiKeyAuth);
        }
    }
});
})();

See more from this issue thread: https://github.com/domaindrivendev/Swashbuckle/issues/222

like image 33
Johnny Qian Avatar answered Sep 28 '22 10:09

Johnny Qian