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?
On ASP.net WebApi, simplest way to pass-in a header on Swagger UI is to implement Apply(...) method on IOperationFilter interface.
Add this to your project:
On SwaggerConfig.cs, register the filter from above using c.OperationFilter<T>():
You can add a header parameter to your request, and Swagger-UI will show it as an editable text box:
You can also add a security definition with type
apiKey
:The
securityDefinitions
object defines security schemes.The
security
object (called "security requirements" in Swagger–OpenAPI), applies a security scheme to a given context. In our case, we're applying it to the entire API by declaring the security requirement a top level. We can optionally override it within individual path items and/or methods.This would be the preferred way to specify your security scheme; and it replaces the header parameter from the first example. Unfortunately, Swagger-UI doesn't offer a text box to control this parameter, at least in my testing so far.
In
ASP.NET Core 2 Web API
, using Swashbuckle.AspNetCore package 2.1.0, implement a IDocumentFilter:SwaggerSecurityRequirementsDocumentFilter.cs
In Startup.cs, configure a security definition and register the custom filter:
In Swagger UI, click on Authorize button and set value for token.
Result:
Here's a simpler answer for the ASP.NET Core Web Api/Swashbuckle combo, that doesn't require you to register any custom filters. Third time's a charm you know :).
Adding the code below to your Swagger config will cause the Authorize button to appear, allowing you to enter a bearer token to be sent for all requests. Don't forget to enter this token as
Bearer <your token here>
when asked.Note that the code below will send the token for any and all requests and operations, which may or may not be what you want.
Via this thread.
For those who use NSwag and need a custom header:
Swagger UI will then include an Authorize button.
I ended up here because I was trying to conditionally add header parameters in Swagger UI, based on my own
[Authentication]
attribute I added to my API method. Following the hint that @Corcus listed in a comment, I was able to derive my solution, and hopefully it will help others.Using Reflection, it's checking if the method nested down in
apiDescription
has the desired attribute (MyApiKeyAuthenticationAttribute, in my case). If it does, I can append my desired header parameters.