I am trying to add an authorization header to Swagger UI using Node.js Express server. Requests need to have x-auth-token as one of the headers for the API to get authenticated. Below is my app.js code:
const swaggerDefinition = {
info: {
title: 'MySQL Registration Swagger API',
version: '1.0.0',
description: 'Endpoints to test the user registration routes',
},
host: 'localhost:8000',
basePath: '/api/v1',
securityDefinitions: {
bearerAuth: {
type: 'apiKey',
name: 'x-auth-token',
scheme: 'bearer',
in: 'header',
},
},
};
const options = {
// import swaggerDefinitions
swaggerDefinition,
// path to the API docs
apis: ['dist-server/docs/*.yaml'],
};
// initialize swagger-jsdoc
const swaggerSpec = swaggerJSDoc(options);
// use swagger-Ui-express for your app documentation endpoint
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
But that's not adding the header to the requests in Swagger UI. How to fix this issue?
Add the following key to your swaggerDefinition:
security: [ { bearerAuth: [] } ],
This will help you in the ExpressJS app.
add this into swagger.json file
"basePath": "/",
"securityDefinitions": {
"Authorization": {
"type": "apiKey",
"name": "authorization",
"in": "header",
"description": "Authentication token"
}
},
add this code into "paths", in which API you want to use the token.
"security": [
{
"Authorization": []
}
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With