npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@mairu/swagger-ui-apikey-auth-form

v1.2.1

Published

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

Downloads

799

Readme

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/[email protected]/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>
  1. 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');

                  // example using SwaggerUIs fetch api
                  ui.fn.fetch({
                    url: '/authenticate',
                    method: 'post',
                    headers: {
                      Accept: 'application/json',
                      'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(value),
                  }).then(function (response) {
                    const json = JSON.parse(response.data);
                    if (json.token) {
                      callback(null, 'Bearer ' + json.token);
                    } else {
                      callback('error while login');
                    }
                  }).catch(function (err) {
                    console.log(err, Object.entries(err));
                    callback('error while login');
                  });
                },
              }
            },
            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:

  • forms To add credentials fields to an api key authentication you have to add this object with the name of the security definition of the api key as object key and an object with the following options as sub keys.

    • authCallback (required) Callback to perform the api key fetching or creation. The callback will get 2 parameters:
      • values - object with form values
      • callback(error, apiKey) - callback to provide api key or error (string)
    • containerStyle Object with css in react way for the container that holds the fields and the submit button. If not provided the default is used { marginLeft: 20 } The container also has the class auth-container-api-key-form if other styles should be addressed.
    • fields Object of fields to render. If not provided the default is used
        fields: {
          username: {
            type: 'text',
            label: 'Username',
            initialValue: 'hans',
          },
          password: {
            type: 'password',
            label: 'Password',
          },
        },
      every field can have the keys: type, label, initialValue, rowProps, colProps, labelProps and inputProps
    • submitBtnLabel Simple string with Label for the submit button. Default is: 'Get Key with Credentials'
  • localStorage - If you want to keep api keys in the local storage you can configure that here. It is an object with the name of the security definition of the api key as object key and the following options as sub keys.

    • key - Key which is used in localStorage, default would be `SwUI_apiKeyAuth_${name}_${window.location.host}${window.location.pathname}`
    • ttl - Time how long an apiKey should be valid when read from localStorage in seconds, default is 3600 (1 hour)