NodeJS 在 Swagger 文档中添加授权按钮

问题描述 投票:0回答:3

我需要能够将以下按钮添加到 Swagger 的 UI 界面,以便测试人员可以添加“Bearer token”标头并测试 api。

我的swagger的选项定义是:

module.exports = {
    definition: {
        openapi: "3.0.3",
        info: {
            title: "APIs",
            version: "1.0.0",
        },
        servers: [
            {
                url: `http://localhost:${process.env.PORT}`
            }
        ],
        securityDefinitions: {
            bearerAuth: {
                type: 'apiKey',
                name: 'Authorization',
                scheme: 'bearer',
                in: 'header',
            },
        }
    },
    apis: ["./routes/*.js", "app.js"],
};

我的终点如下:

/**
 * @swagger
 * /api/users/test:
 *  post:
 *      security: 
 *          - Bearer: []
 *      summary: test authorization
 *      tags: [User]
 *      description: use to test authorization JWT
 *      responses:
 *          '200':  
 *              description: success
 *          '500':
 *                  description: Internal server error
 */

router.post('/test', verifyJWT(), async (req, res) => {
    res.send('hi');
})
javascript node.js typescript swagger
3个回答
5
投票

您使用的是 OAS v3 吗?您的声明中有错误,例如

securityDefinitions
现在称为
securitySchemes
并且位于
components
内。

检查https://swagger.io/docs/specification/authentication/

修复架构后,您可以向路径添加

security
属性,以使用安全架构保护它,这样您将获得绿色
Authorize
按钮。

components:
  securitySchemes:

    BearerAuth:
      type: http
      scheme: bearer
paths:
   /api/users/test:
     post:
       security: 
         - BearerAuth: []

1
投票

对于 Node 项目中的 swagger-ui-express 4.6.3

  1. 在 swagger.json 文件中添加 securityDefinitions,如下所示。

*注意:bearerAuth 的安全参数必须相同

2.在swagger.json文件中的每个路径或API中添加安全参数

 "securityDefinitions": {
  "bearerAuth": {
    "type": "apiKey",
    "in": "header",
    "name": "Authorization",
    "description": "Bearer token to access these api endpoints",
    "scheme": "bearer"
  }
}

"security": [
      {
        "bearerAuth": []
      }
    ]

0
投票

授权中缺少“承载者”。

© www.soinside.com 2019 - 2024. All rights reserved.