Edit July 2018: I’ve blogged a better way to do this. 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. Fortunately (if you’re using ASP.NET), Swashbuckle 5.0 is extendable, so it’s very easy to add a new IOperationFilter to do it for us:
public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter { public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) { if (operation.parameters != null) { operation.parameters.Add(new Parameter { name = "Authorization", @in = "header", description = "access token", required = false, type = "string" }); } } }
Now all you need to do is register it in your EnableSwagger call:
configuration .EnableSwagger(c => { c.SingleApiVersion("v1", "Commerce Services - Discounts"); foreach (var commentFile in xmlCommentFiles) { c.IncludeXmlComments(commentFile); } c.OperationFilter<ExamplesOperationFilter>(); c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>(); }) .EnableSwaggerUi(config => config.DocExpansion(DocExpansion.List));
Once that’s done it’ll give you an input field where you can paste your Authorization header. Don’t forget to add the word “bearer” if you’re using a JWT token:
Edit July 2018: I’ve blogged a better way to do this. Add an authorization header to your swagger-ui with Swashbuckle (revisited).
Still works. Thanks!
Works with Swashbucke 5.6.0 as well
Thanks for sharing. This only works for POSTs. My apis have some GETs that require a token and no other inputs, params, etc, Therefore the authorization input field does not show for this.
I’ve just blogged a better way of doing this, which should work for GETs https://mattfrear.com/2018/07/21/add-an-authorization-header-to-your-swagger-ui-with-swashbuckle-revisited/
Put these lines of code.
if (operation.parameters == null)
{
operation.parameters = new List();
}
Brilliant!
Brilliant!
YES!
I’ve blogged a better way to do this here https://mattfrear.com/2018/07/21/add-an-authorization-header-to-your-swagger-ui-with-swashbuckle-revisited/
How do I use this but exclude it from one or two methods?
I recommend you do it the correct way, as blogged here https://mattfrear.com/2018/07/21/add-an-authorization-header-to-your-swagger-ui-with-swashbuckle-revisited/
If done that way then it will only be present for whichever of your actions have an [Authorize] attribute.
Ok I have a doubt in my scenario, I want to pass the token to all the default headers in each API the user needs to accept.