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

We use Swashbuckle to document our web apis and use it to test our web avis. I want to know how you can pass multiple custom headers with different values ​​for each request using the Swagger user interface.

I saw an answer similar to the one below on the web to pass the header in the Swagger user interface, but couldn't tear it off. What is confusing about the SwaggerExtensions file. What is the purpose of this file and why is this file mentioned in the qualified js file name.

1. Add a new file called "SwaggerExtensions" and then add a new JS file called "onComplete.js", you need to change the build action for this file to "Embedded Resource".

2. Inside the "onComplete.js" file, 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 the file "SwaggerConfig.cs" and inside the register method, paste the following code:

 SwaggerUiConfig.Customize(c => { c.SupportHeaderParams = true; c.InjectJavaScript(typeof(SwaggerConfig).Assembly, "AngularJSAuthentication.API.SwaggerExtensions.onComplete.js"); }); 
+10
asp.net-web-api swagger-ui
source share
4 answers

The swashbuckles swagger implementation reads XML comments to generate the required swagger specification. Unfortunately, if you need an authorization header (access token) for requests, XML code comments do not provide this information to Swashbuckle. You will have to manually enter this new parameter while generating the swagger specification.

Swashbuckle provides an IOperationFilter interface for applying new options. The implementation of 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())); } } 
+8
source share

Swashbuckle suggests using InjectJavaScript to accomplish this. https://github.com/domaindrivendev/Swashbuckle#injectjavascript

I am using the following code to add a carrier token for authorization in the 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); } } }); })(); 

More on this release: https://github.com/domaindrivendev/Swashbuckle/issues/222

+6
source share

You can add a parameter using SwaggerUI:

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

I stumbled upon this question when trying to add a custom header containing some authentication information. This article provides a way to do this without implementing JavaScript (a clean .NET approach) by providing SecurityDefinition when setting up 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 is always for defining a security token at the API level or method level (a kind of logon), and this token will be used for all subsequent requests before logging out.

0
source share

All Articles