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
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).
A Demo of Swagger UI using this plugin as available here.
The credentials for the api key authentication are user
with password secret
;
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.
<script src="./swagger-ui-apikey-auth-form.js"></script>
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: {}
}
}
}
});
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:
{ marginLeft: 20 }
The container also has the class auth-container-api-key-form
if other style should be addressed. fields: {
username: {
type: 'text',
label: 'Username',
},
password: {
type: 'password',
label: 'Password',
},
},
every field can have the keys: type, label, rowProps, colProps, labelProps and inputProps
`SwUI_apiKeyAuth_${name}_${window.location.host}${window.location.pathname}`