I have some endpoints in the API - /user/login
, /products
.
In Swagger UI I post email
and password
to /user/login
and as a response I receive a token
string.
Then, I can copy the token from the response and want to use it as Authorization
header value in requests to all urls if it's present, and to /products
as an example.
Should I create a text input manually somewhere on the Swagger UI page, then put the token there and somehow inject in the requests or are there tools to manage it in a better way?
After add settings, then run this project, you can find an Authorization button swagger page, and you can use it to set the authorization header. Show activity on this post. then in SwaggerUIBundle constructor: const ui = SwaggerUIBundle({ ..., requestInterceptor: function (req) { req.
In ASP.NET Web API, the simplest way to pass-in a header on Swagger UI is to implement the Apply(...) method on the IOperationFilter interface.
You can pass multiple header params on a single request, just use unique names for them (key is used in the above example). To be clear, both headers are added to Access-Control-Allow-Headers, and both can be recived separatelly by server, the case is that i'm not able to send them together.
In ASP.NET Web API, the simplest way to pass-in a header on Swagger UI is to implement the Apply(...)
method on the IOperationFilter interface.
Add this to your project:
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 = "MyHeaderField", @in = "header", type = "string", description = "My header field", required = true }); } }
In SwaggerConfig.cs, register the filter from above using c.OperationFilter<T>()
:
public static void Register() { var thisAssembly = typeof(SwaggerConfig).Assembly; GlobalConfiguration.Configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "YourProjectName"); c.IgnoreObsoleteActions(); c.UseFullTypeNameInSchemaIds(); c.DescribeAllEnumsAsStrings(); c.IncludeXmlComments(GetXmlCommentsPath()); c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First()); c.OperationFilter<AddRequiredHeaderParameter>(); // Add this here }) .EnableSwaggerUi(c => { c.DocExpansion(DocExpansion.List); }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With