AspNet Core 2 Swagger UI: JWT authorization problem
See original GitHub issueI have an ASP.NET Core 2 app and added NSwag to it. I use UseSwaggerUi3WithApiExplorer() and all my controllers/actions show up on the swagger ui page.
Most of my actions require a valid JWT. I’ve found the following posts, but none of them were working for my case:
- https://stackoverflow.com/questions/46236152/implement-jwtbearer-authentication-in-nswag-swaggerui
- https://github.com/RSuter/NSwag/issues/869#issuecomment-368614010
Cause I’m still undecided between NSwag and Swashbuckle, I’ve tried to do the same with Swashbuckle, following this guide: https://ppolyzos.com/2017/10/30/add-jwt-bearer-authorization-to-swagger-and-asp-net-core/
With Swashbuckle, I get the Authorize button with no problem, I can add my JWT ('Bearer ’ + token) and then successfully call the protected actions.
I compared the generated swagger.json files and noticed, that the Swashbuckle version includes this at the end:
"securityDefinitions": {
"Bearer": {
"name": "Authorization",
"in": "header",
"type": "apiKey",
"description": "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\""
}
},
"security": Array[1][
{
"Bearer": Array[0][
]
}
]
whereas the NSwag swagger.json file does not include any securityDefinitions/security entries.
Issue Analytics
- State:
- Created 5 years ago
- Comments:8 (4 by maintainers)
I found the problem! For some reason (probably cause I was copy/pasting code from various locations into my sample project), I had in my Configure() the following code:
Only the UseSwaggerWithApiExplorer() got applied then, the call to UseSwaggerUi3WithApiExplorer() was basically ignored (or at least the GeneratorSettings in there, the DocExpansion worked).
So I changed it to the following, and now it’s displaying the Authorize button and WORKING:
Of course 😃
I am using this
I was hoping to fix this by just changing these settings 😉 If I need to use
PostProcess
or something else, I won’t bother. It’s not that important, but it’s a shame that the behavior is a bit different 😃