I'm creating a REST api in ASP.NET Core 1.0. I was using Swagger to test but now I added JWT authorization for some routes. (with UseJwtBearerAuthentication
)
Is it possible to modify the header of the Swagger requests so the routes with the [Authorize]
attribute can be tested?
Currently Swagger has functionality for authentication with JWT-token and can automatically add token into header (I'm using Swashbuckle.AspNetCore 1.1.0).
The following code should help achieve this.
In the Startup.ConfigureServices():
Check and configure TokenUrl if your endpoint is different.
In the Startup.Configure():
If your endpoint for authentication by token follows the OAuth2 standard, all should work. But just in case, I have added sample of this endpoint:
Thanks to the Pavel K.'s answer, this is the way I finally resolved this issue in ASP.NET Core 2.2 with Swagger 4.0.1.
In the Startup.cs ConfigureServices():
In the Startup.cs Configure():
And here is how I made an endpoint to give out a JWT token:
All your rules and logic on validating user name and password (and/or client_id and clinet_secret) will be in
ValidateCredentialAndGenerateClaims()
.If you just wonder, these are my request and response models:
To expand on HansVG answer which worked for me (thanks) and since I don't have enough contribution points I can't answer emseetea question directly. Once you have the Authorization textbox you will need to call the endpoint that generate the token which will be outside your must [Authorize] area of endpoints.
Once you have called that endpoint to generate the token from the endpoint you can copy it out of the results for that endpoint. Then you have the token to use in your other areas that are must [Authorize]. Just paste it in the textbox. Make sure, as HansVG mentioned, to add it in the correct format, which needs to include "bearer ". Format = "bearer {token}".
I struggled with the same problem and found a working solution in this blogpost: http://blog.sluijsveld.com/28/01/2016/CustomSwaggerUIField
It comes down to adding this in your configurationoptions
and the code for the operationfilter
Then you will see an extra Authorization TextBox in your swagger where you can add your token in the format 'Bearer {jwttoken}' and you should be authorized in your swagger requests.