'Nodejs Swagger unable to add authorization header to requests
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?
Solution 1:[1]
Add the following key to your swaggerDefinition
:
security: [ { bearerAuth: [] } ],
Solution 2:[2]
If You are using Node and Express js in your swagger file for example in swagger.json add an authorization header like this
"securityDefinitions": {
"AuthToken": {
"type": "apiKey",
"name": "auth-token",
"in": "header",
"description": "The token for authentication"
}
},
"security": [
{
"AuthToken": []
}
],
Note: Security property is outside securityDefinitions object.
Please vote this answer to help others
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Helen |
Solution 2 | Ndatimana Gilbert |