Sunday, July 29, 2018

Using Swashbuckle or Swagger-UI 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. The sad part is that currently Swagger-UI 3.17.6 doesn't play well with Auth0.  After spending more than a few hours trying to configure OAuth2 via the Swashbuckle, I realized that the underlying code doesn't support the passing of an audience parameter. https://github.com/swagger-api/swagger-ui/issues/4533

Our API needs user information. To test it from Swagger-UI we needed to be able to execute an Implicit Grant flow, and then use the authorize token from that flow in proceeding calls in the authorization header.

Given the currently somewhat crippled capability of Swagger-UI, and the need to still get things done, I settled on a pragmatic but not all that clever solution.

I decided to override the version of Swagger-UI that comes packaged with Swashbuckle, and in doing so add in a little code to accomplish what I wanted. In the image below you can see an additional 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 is extracted and shown in a prompt for the user to copy to the clipboard. The user must then hit the authorize button and paste the code from the clipboard into the dialog at which point they are logged in.

While this may sound terrible, it's a good deal easier than logging into another application and pulling an access token out using Fiddler...






The secret to this working is that 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 the gist above.  If your using Swashbuckle over-ride 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");

If you find yourself using Swagger and Auth0, you might find yourself doing something similar. :)

3 comments:

  1. I'm amazed more people haven't posted about this. Are you aware of there being a solution yet?

    ReplyDelete
  2. I took a look at the source code, I think a patch for this would be quiet simple. However, given time constraints I hacked a solution together that worked for us...

    ReplyDelete
  3. Did this ever get resolved, im also having this issue - hard to believe these 2 dont play well with each other..

    ReplyDelete