Using Swashbuckle Authorize Button with Auth0
Auth0 is a great solution for authentication. Swagger-UI is great for kicking the tires on your API. If your using .Net you can pull in Swashbuckle, which is a .Net wrapper of Swagger. In development I use Swagger often and I found that the Authorize step was tedious. I would use another API client like Postman to call Auth0 API. Executing an implicit grant flow, in Auth0 yielded an Auth token which is copied to the clipboard. Then I'd click the Authorize button in Swagger and type Bearer and paste in my token. Exhausting! In this post I will show you a little trick that will make life simpler.
The Authorize button in the top right corner of the Swagger page is configurable. The sad part is that currently Swagger-UI 3.17.6 doesn't play well with Auth0. Short story is Swagger does not support the passing of an audience parameter. Here is a Github issue with the details.
Given the situation with Swagger-UI. I thought of forking Swashbuckle and patching things up. This seemed tedious and I tend to fork only as a last resort. I settled on a pragmatic but not all that clever solution. I realized Swashbuckle would let me replace the version of Swagger-UI it comes packaged with. That would let me add in a little hack to create a cleaner authorization workflow.
In the image below you can see an extra button in the UI. [Get Auth Token]. This button hits the API endpoint which redirects to Auth0. The user logs in, and is redirected back to the Swagger-UI endpoint. The token is in the URL, and gets extracted and shown in a prompt for the user to copy to the clipboard. The user then clicks the Swagger Authorize button. When the Swagger Auth dialog appears they paste the clipboard contents into it. This is much quicker!
The secret to getting this working is Swashbuckle allows you to specify a new index file. Download the Swagger-UI source from Github and keep the following files. Set the index files build action to embedded resource in Visual Studio.
Replace the body of the code in index with the code body of the index file from this Gist. Note: the rest of the code you'll need to wire this in should also be in the Gist. If your using Swashbuckle override the default index with your modified file by setting the IndexStream in the config.
c.IndexStream = () => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("Project.API.Swagger.index.html");
Hopefully, someday something similar to this will be supported natively in Swagger.