naveen
naveen

Reputation: 117

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?

Upvotes: 3

Views: 13301

Answers (3)

Sandeep kumar
Sandeep kumar

Reputation: 31

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": []
  }
]

Upvotes: 2

Ndatimana Gilbert
Ndatimana Gilbert

Reputation: 329

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

Upvotes: 0

Helen
Helen

Reputation: 97540

Add the following key to your swaggerDefinition:

  security: [ { bearerAuth: [] } ],

Upvotes: 7

Related Questions