NSwag.AspNetCore SwaggerUI: how to add JWT authorization headers?
See original GitHub issueHello, I’m successfully running my AspNetCore WebAPI project with JWT authorization and MS API versioning, but can’t understand how to properly configure NSWag middleware to expose the “Authorization: Bearer” token, so to properly generate a c# client library using NSWag Studio.
I’m actually getting a timeout when opening my API project /swagger endpoint: it shows Swagger page, but then it stands waiting for it to show my api methods (fetching resource list). No errors appear on server, and the json can be loaded at its url. Can’t even tell if this problem is related with the authorization header not being correctly generated.
My Configure method contains:
[...]
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters,
Events = new MyCustomJWTEventHandler()
});
// Swagger
SwaggerUiSettings options = new SwaggerUiSettings();
options.Description = "My API";
options.Version = "1.0.0";
options.Title = "My API";
options.ValidateSpecification = true;
// add Authorization header to Swagger UI
options.OperationProcessors.Add(new OperationSecurityScopeProcessor("apiKey"));
options.DocumentProcessors.Add(new SecurityDefinitionAppender("apiKey", new NSwag.SwaggerSecurityScheme()
{
Type = NSwag.SwaggerSecuritySchemeType.ApiKey,
Name = "Authorization",
In = NSwag.SwaggerSecurityApiKeyLocation.Header,
Description = "Bearer token"
}));
app.UseSwaggerUi(typeof(Startup).GetTypeInfo().Assembly, options);
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller}/{action}/{id?}");
});
The produced json contains a security node for each method, but I’m not sure this is correct - and NSWag studio does not add code to handle the authorization header to the generated client library.
"security": [
{
"apiKey": []
}
]
Can anybody help me taking the right direction? 😚
Thanks for any help,
al.
Issue Analytics
- State:
- Created 6 years ago
- Comments:44 (18 by maintainers)
Any success adding JWT tokens from SwaggerUI? I can make it work in Angular 5 with the nwag generated JS client, but can’t figure out how to successfully tweak the SwaggerUI through UseWaggerUI3 in the .Net Core server side settings. To be more precise, SwaggerUI2 is able to add the apiKey token on the request retrieving swagger.json definition, but they are not added to the “try it out” functionality, i.e. in the curl commands.
My bad, I confused the name and the ApiKey type, this does work:
Pay attention to the reference between the “JWT token” name in OperationSecurityScopeProcessor and the name in SecurityDefinitionAppender.
Here’s how you get JWT tokens working with v12.0.14 (.NET Core 2.2):