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

swagger add header parameters c
swagger send custom headers
swagger ui add authorization header c
swagger ui add custom header
swagger 2.0 request header example
ioperationfilter swagger .net core
swagger basic authentication example c
swagger request headers example java

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");
});

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("team@team.com"));

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


      }
 }

Web Api How to add a Header parameter for all API in Swagger , You can find the answer on GitHub here: AddRequiredHeaderParameter using System. Mvc.ApiExplorer; using Swashbuckle. What the user "G T" wrote is correct but it is not working with Swagger 5. We have some Another way to add custom headers is by adding parameters into controller action. Adding a Required HTTP Header to Your Swagger UI With Swashbuckle If you’re building ASP.NET Core Web APIs, then I hope you’ve heard of Swashbuckle – the tool to generate the Swagger UI automatically for all of your controllers to make manual testing your endpoints visual and simple.

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

Adding a Required HTTP Header to Your Swagger UI With , NET Core Web APIs, then I hope you've heard of Swashbuckle - the tool to for your custom HTTP Request Headers so you can fill them out while testing without SwaggerEndpoint( "/swagger/v1/swagger.json" , "My API v1" );. }); Let's create a MyHeaderFilter and then add it to the AddSwaggerGen call. 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.

You can add a parameter with SwaggerUI :

swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("api_key", key, "header"));

Swashbuckle (Swagger) Customization for WebAPI, The article describes how to bind Swagger customization to the project Deploying WebAPI into production may cause the issue when the XML file is missing. The proxy adds headers to the request, by which we know what URL of for one endpoint, the call of which depends on the query parameters. I require to add authorization token in the request headers while making the API calls, is there a way to configure this on the UI? My Swagger Configuration file looks like this - @Configuration @EnableSwagger2 @ComponentScan ( basePackages = " com.rokitt.** " ) public class SwaggerConfiguration { @Bean public Docket petApi () { return new Docket ( DocumentationType .

I have stumbled across this question when trying to add a custom header containing some authentication information. This article suggests a way to accomplish this without injecting JavaScript (pure .NET approach) by providing a SecurityDefinition when configuring swagger integration:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1.0", new Info { Title = "Main API v1.0", Version = "v1.0" });

    // Swagger 2.+ support
    var security = new Dictionary<string, IEnumerable<string>>
    {
        {"Bearer", new string[] { }},
    };

    c.AddSecurityDefinition("Bearer", new ApiKeyScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = "header",
        Type = "apiKey"
    });
    c.AddSecurityRequirement(security);
});

This always to define a security token at API level or method level (some sort of log in) and this token will be used for all subsequent requests until logged out.

How to pass custom headers when calling web api using Swagger , The swashbuckles swagger implementation reads XML comments to generate the required swagger specification. Unfortunately, if you need an authorization  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more . Web Api How to add a Header parameter for all API in Swagger. Ask Question Asked 3 years, 5 months ago. Active 29 days ago. Viewed 3

Add an authorization header to your swagger-ui with Swashbuckle , Add an authorization header to your swagger-ui with Swashbuckle (revisited). Out of the box there's no way to add an Authorization header to your API requests from swagger-ui. Now all you need to do is register it in your EnableSwagger call: By continuing to use this website, you agree to their use. The goal is to add the header Authorization: Basic base64 string here to the request sent out using the Try it out button without using the Authorization modal and without using the default menu that opens in chrome. I'm guessing this may already be there I just can't find it. In v2.x I was using

Customize Authentication Header in SwaggerUI using Swashbuckle, Although that works, Swagger-UI and Swashbuckle support a better way, got OAuth2 setup correctly on your application (using bearer tokens), header with your bearer token should be sent to your API. On my web api I need to acces http://mysite/token passing username, password and grant_type. In this case, Swagger will stop showing any information, as the handler will not allow passing queries. It is not solved out of the box, that’s why it is necessary to make provision for this case in your handler, i.e. in the case of a query to the swagger URL, the handler should pass it. And then the addition of headers with JS will help, as described above.

mattfrear/Swashbuckle.AspNetCore.Filters: A bunch of , Customize Authentication Header in SwaggerUI using Swashbuckle established itself as an important tool for building Web API's for any platform. For example, by default Swagger UI gives you a textbox for for the "API key". When you execute the request, it simply puts this API key into a query string  When I first tried using Swagger with Web API I spent a little time looking through the configuration files and it seemed a little confusing to me. I did a little research and I came across Swashbuckle which makes adding Swagger UI into your asp.net Web API project a no brainer. It can hook right into your Startup Configuration class and should only take a few minutes to get the basics up and

Comments
  • But, I want to pass the header value from the UI (Swagger-UI). How to pass the value of the header ?
  • Thanks @nimacks, this worked for me. Although for some reason my operation.parameters was null, so I added a check that will intialise it if it's null before adding the parameter required.
  • You may also need to add the following line of code before adding the operation.parameters: if (operation.parameters == null) operation.parameters = new List<Parameter>();
  • what is the containingAssembly?
  • containingAssembly = typeof(SwaggerConfig).Assembly; where SwaggerConfig is the class holding the config for swagger.