Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 355
naveen Avatar asked Jan 19 '26 00:01

naveen


2 Answers

Add the following key to your swaggerDefinition:

  security: [ { bearerAuth: [] } ],
like image 183
Helen Avatar answered Jan 21 '26 20:01

Helen


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": []
  }
]
like image 42
Sandeep kumar Avatar answered Jan 21 '26 21:01

Sandeep kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!