Nodejs Swagger 无法向请求添加授权 header

Nodejs Swagger unable to add authorization header to requests

我正在尝试使用 Node.js Express 服务器向 Swagger UI 添加授权 header。请求需要 x-auth-token 作为 header 之一,API 才能通过身份验证。下面是我的 app.js 代码:

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));

但这并不是将 header 添加到 Swagger UI 中的请求中。如何解决这个问题?

将以下密钥添加到您的 swaggerDefinition

  security: [ { bearerAuth: [] } ],

如果您在 swagger 文件中使用 Node 和 Express js,例如在 swagger.json 添加授权 header 像这样

    "securityDefinitions": {
    "AuthToken": {
      "type": "apiKey",
      "name": "auth-token",
      "in": "header",
      "description": "The token for authentication"
    }
  },
"security": [
    {
      "AuthToken": []
    }
  ],

注意:安全 属性 在 securityDefinitions object 之外。

请投票给这个答案以帮助其他人