Nodejs Swagger无法向请求添加授权头信息。

3

我正在尝试使用Node.js Express服务器向Swagger UI添加授权标头。请求需要将x-auth-token作为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));

但是这并没有将头部添加到Swagger UI中的请求。如何解决这个问题?
3个回答

7
将以下键添加到您的 swaggerDefinition 中:
  security: [ { bearerAuth: [] } ],

2

这将有助于您在ExpressJS应用程序中使用。

将此添加到swagger.json文件中

"basePath": "/",
"securityDefinitions": {
    "Authorization": {
    "type": "apiKey",
    "name": "authorization",
    "in": "header",
    "description": "Authentication token"
  }
},

将此代码添加到“paths”中,其中包含您想要使用令牌的API。

"security": [
  {
     "Authorization": []
  }
]

0
如果您在Swagger文件中使用Node和Express JS,例如在swagger.json中添加授权标头,可以像这样添加:
    "securityDefinitions": {
    "AuthToken": {
      "type": "apiKey",
      "name": "auth-token",
      "in": "header",
      "description": "The token for authentication"
    }
  },
"security": [
    {
      "AuthToken": []
    }
  ],

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

请投票支持此答案,以帮助他人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接