Swagger interface: skip user authorization header

I use Swashbuckle and Swagger in the ASP.NET Web API. I am trying to find a way to pass an authorization header containing a carrier token through the Swagger interface. I searched, but all answers seem to point to this link.

However, this assumes that the contents of the header are known in advance. I really need a way to change the title in the Swagger user interface (right before clicking the Try Now button), because the Bearer token expires every hour. Something similar to the way the postman allows you to add headers.

Such a ridiculously simple problem seems to be, but what is the answer?

+6
source share
3 answers

We faced the same problem in our project. I also wanted to add header options to the Swagger UI website. Here's how we did it:

1. Define the class OperationFilter OperationFilters are executed on each API operation each time you create a Swagger. According to your code, operations will be checked according to your filters. In this example, we make the header parameter mandatory for each operation, but make it optional for operations with 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 SwaggerConfig, simply add that the working filter should be used as follows:

 c.OperationFilter<AddAuthorizationHeader>(); 

Hope this helps you!

+14
source

You can do this differently depending on how you compile the Authorization header and whether you want the code to handle everything or if you want the user to enter the Authorization header that they want.

When I first tried this, I was able to show the Authorization header text in each area of ​​the endpoint parameter field, where the user could enter the Authorization header, but that was not what I wanted.

In my situation, I had to send a request to the /token endpoint using a user cookie in order to get a valid Authorization token. So I did something to achieve this.

First, in SwaggerConfig.cs I uncommented c.BasicAuth() to get the main auth scheme in the API scheme, and I also added a custom index.html page where I inserted an AJAX request to capture the Authorization token using the user's cookie ( index.html 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 run here to download the swashbuckle index.html , which we will configure to insert the Authorization header.

Below, I just make an AJAX call to my endpoint /token with a valid cookie, get the Authorization token and pass it to swagger for 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 simpler and obviously your implementation will probably differ depending on how you collect the token, etc., but this gives you an idea. If you have any specific questions or questions, let me know.

* Edit: I didn’t notice that you really wanted the user to enter their Authorization header. In this case, it is very easy. I used this post. Just create the following class to do the job:

 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 we added the class to my SwaggerConfig as follows:

 ... c.OperationFilter<AddRequiredHeaderParameter>(); ... 
+1
source

Create a new work 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 the Startup.cs file.

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

All Articles