swagger-ui-apikey-auth-form

Swagger UI Plugin to allow login with credentials for apiKey authentications and keep apiKey in localStorage

View the Project on GitHub Mairu/swagger-ui-apikey-auth-form

Swagger UI Plugin ApiKeyAuthForm

npm

A plugin for Swagger UI to authenticate using credentials to generate a token which is used as apiKey header. Works also for bearer authentication of OpenApi V3. Also keeps an api token in the localStorage if configured, which helps with page reloads (on development).

Demo

A Demo of Swagger UI using this plugin as available here. The credentials for the api key authentication are user with password secret;

Compatibility

The plugin was developed using Swagger UI Version 3.22. As it uses internal APIs of Swagger UI, they could change and break the plugin.

Usage.

  1. Make swagger-ui-apikey-auth-form.js available for use in your Swagger UI. There are different possibilities:
    • Load it using https://unpkg.com/@mairu/swagger-ui-apikey-auth-form@1.0.0/dist/swagger-ui-apikey-auth-form.js (directly or copy to your project)
    • Include ‘@mairu/swagger-ui-apikey-auth-form’ to your dependencies and serve it from node_modules.
  2. Include this script in your Swagger index.html (adjust the path to the method you use)
    <script src="./swagger-ui-apikey-auth-form.js"></script>
    
  3. Then add the plugin to your Swagger UI config and also add needed configuration
      const ui = SwaggerUIBundle({
        // ...
        plugins: [
          // ...
          SwaggerUIApiKeyAuthFormPlugin,
        ],
        // ...
        configs: {
          apiKeyAuthFormPlugin: {
            forms: {
              apiKeyName: {
                fields: {
                  fieldName: {
                    type: 'text',
                    label: 'Fieldname',
                  },
                  // ...
                },
                authCallback(values, callback) {
                  // do login stuff
                  
                  // on error
                  callback('error message');
                  
                  // on success
                  callback(null, 'the api key here');
                },
              }
            },
            localStorage: {
              apiKeyName: {}
            }
          }
        }
      });

Configuration

The Plugin has to be configured to know for which apiKey a form should be added to the SwaggerUI and how to handle authentication. For that you have to add the plugin config object in the configs of the SwaggerUI initialization with key name apiKeyAuthFormPlugin.

Here are the config options of the plugin config: