NodeJS 将授权按钮添加到 Swagger 文档

NodeJS add the authorization button to Swagger Documentation

我需要能够将以下按钮添加到 Swagger 的 UI 界面,以便测试人员可以添加“Bearer token”header 并测试 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');
})

您使用的是 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: []