Swagger-ui: How to integrate with jwt based authentication?

Created on 9 Jan 2015  路  32Comments  路  Source: swagger-api/swagger-ui

I set up a little example that shows how to build a minimal Todo backend using Express, jwt and co. The problem is that swagger-ui relies on api key. I noticed it's possible to customize this a little bit (ie. push api key to header) but that doesn't solve the problem entirely.

I would need some way to log in to the system first. I will be able to get the token required by authentication through that.

An extra challenge is how to make this all work nicely with swagger-tools but that's a separate problem. If there was a nice extension point for something like this, it would probably be easier to handle that side. I would just need something that can be plugged into an Express middleware and served as a static site through it.

feature

Most helpful comment

I hacked this into index.html today to get it working. I changed the addApiKeyAuthorization implementation to the following:

      function addApiKeyAuthorization(){
        var key = encodeURIComponent( $('#input_apiKey')[0].value );
        if(key && key.trim() != "") {
            var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization( "Authorization", "Bearer " + key, "header" );
            window.swaggerUi.api.clientAuthorizations.add( "bearer", apiKeyAuth );
            log( "Set bearer token: " + key );
        }
      }

The security definition in my swagger.json looks like this:

  "securityDefinitions": {
    "bearer": {
      "type": "apiKey",
      "name": "Authorization",
      "in": "header"
    }
  }

Token is now being set in the headers for each request where I indicate the "bearer" security is required. I'll likely tack on a little localStorage magic to store the token in the browser to persist beyond reloads.

Hope this helps someone

All 32 comments

Hi, I'm not sure exactly what you mean. Can you please elaborate? Most people customize the index.html file for swagger-ui and bring in the javascript portions.

I guess the ideal would be that I could consume swagger-ui as a dependency of my project, inject the changes I need (ie. way to log in -> auth header) and serve it through a middleware.

If this isn't feasible, I suppose I could just maintain a copy of swagger-ui within the project itself. It looks like this is exactly what swagger-tools is doing.

We have the same situation as @bebraw. We are also using JWT (http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html), which basically requires a custom Authorization header for the API calls. I would be OK if I could just paste the token I receive from my server into an Authorization header field for the remainder of the API calls.

It may be an issue with the spec itself. Based on http://oauth.net/documentation, it looks like JWT is an extension of OAuth2, though I'm not sure how it comes in to play. It looks like it can be integrated with the implicit (bearer) flow, which is already supported by Swagger, but I'm not sure whether that requires any additional extensions.

Does anyone have more information regarding this, some sort of instructions or tips on how to implement the authentication process and adding the token to the header during all calls?

ditto @Todilo

@Todilo @jackphel please see here:

https://github.com/swagger-api/swagger-js/blob/master/README.md#custom-request-signing

@fehguy Thanks for your quick response! I got that working with swagger-ui. I think I should add jwt as a header token in https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#security-scheme-object- though I'm not sure whether it's exactly a great fit because the token encodes a json object with data specific to the user's context rather than an api key.

I hacked this into index.html today to get it working. I changed the addApiKeyAuthorization implementation to the following:

      function addApiKeyAuthorization(){
        var key = encodeURIComponent( $('#input_apiKey')[0].value );
        if(key && key.trim() != "") {
            var apiKeyAuth = new SwaggerClient.ApiKeyAuthorization( "Authorization", "Bearer " + key, "header" );
            window.swaggerUi.api.clientAuthorizations.add( "bearer", apiKeyAuth );
            log( "Set bearer token: " + key );
        }
      }

The security definition in my swagger.json looks like this:

  "securityDefinitions": {
    "bearer": {
      "type": "apiKey",
      "name": "Authorization",
      "in": "header"
    }
  }

Token is now being set in the headers for each request where I indicate the "bearer" security is required. I'll likely tack on a little localStorage magic to store the token in the browser to persist beyond reloads.

Hope this helps someone

@Qwerios thank you very much for your guide. that is really helps me. i didnt know if bearer between swaggerUi.api.clientAuthorizations.add() and securityDefinitions must be same

:+1: for @Qwerios' solution. Many thanks.

for @Qwerios

+1 for @Qwerios

+1 for @Qwerios

Hi, by using @Qwerios 's solution, the header is sent for all routes, and it didn't checking that swagger spec has security defined or not.

Applying the apiKey is done inside the swagger-ui.js. For testing with the swagger UI setting the token for each call is never a problem for my scenarios. If I need to call unauthenticated I just emtpy the bearer token input field.

I'm afraid I don't have intimate knowledge of how the swagger-ui code works internally nor do I have the time to dive into it.

@Qwerios , But in my application , for some urls the token must not be used.

Here is a related approach to add JWT support into Swagger UI project (swagger-api/swagger-ui#2234). This adds a new 'jwt'-type authorization scheme with login-support in the Swagger UI.

However, to get it this pull request integrated in the Swagger UI, support for JWT based authentication needs to be added in the OpenAPI specification first.
If somebody has some time to spare on this, it would be gladly appreciated.

+1 for adding a feature similar to @Qwerios solution

+1 for this feature

The approach outlined by @Qwerios here https://github.com/swagger-api/swagger-ui/issues/818#issuecomment-113185459 no longer works in swagger-ui-2.2.5

Authorization input has been broken out into a dialog window

The documentation here does not reflect that change: https://github.com/swagger-api/swagger-ui

Adding a header to every request per the docs also does not work for me:

If you have some header parameters which you need to send with every request, use the headers as below:

swaggerUi.api.clientAuthorizations.add("key", new SwaggerClient.ApiKeyAuthorization("Authorization", "XXXX", "header"));

Adding just Bearer <token> as API key seemed to work for me.

Disclaimer: I use Clojure's metosin/ring-swagger-ui version 2.1.4-0 and override its base index.html with swagger-api/swagger-ui's index.html from version 2.2.8 in my resources folder.

I've recently had great success using a legitimate AuthorizationCode flow initiated by swaggerUI. If your token is provided by an authorization server that correctly implements the flow, I'm sure this is the best option.

I've not directly tested implicit or password grants, but IIRC I've seen documentation stating they are supported

The OpenAPI spec now has a merged PR that adds support for bearer/JWT authentication. They plan to release this as an Implementer Draft on February 28, 2017.

After that, I assume that the next step would be for this project to implement @K1ll3rF0x 's PR (or similar) to add support on this side for the newly official JWT/bearer authentication.

The next step would be for this tool to support the entire spec, yes, which would include support for JWT/bearer authentication.

Any update on this?

We're working on 3.0 support, but it's going to take a while, especially to support the entire spec.

In the meantime, has anyone come up with a temporary way of adding JWT based authentication to Swagger UI 3.0.8?

Closing this ticket out. The comments have a suggested solution for the previous version.

@pqzxc we're working on bringing back a similar functionality to the current version.

3.0 support is in process. Right now we're working only on the rendering, but when the try it out functionality is introduced, the jwt support will be included in it.

@webron is there any issue we can follow (since this is closed) so that we know when JWT is supported in the UI?

Maybe we could keep this one open so that we can track the status of this feature in any way. I'm waiting for this to be resolved to migrate my company's projects to Swagger.

^ +1

@webron

For those of you who are migrating to OAS3 and use JWT... take a look at https://github.com/swagger-api/swagger-ui/issues/3641#issuecomment-337745237.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

easyest picture easyest  路  3Comments

songtianyi picture songtianyi  路  3Comments

deepumi picture deepumi  路  3Comments

prabhat1790 picture prabhat1790  路  3Comments

MartinMuzatko picture MartinMuzatko  路  4Comments