如何使用 JWT 令牌授权 Swagger jsdoc?

akh*_*301 1 node.js jwt swagger swagger-ui swagger-2.0

我已经定义了我的 swagger 定义,如下所示:

const swaggerDefinition = {
  info: {
    title: 'Node Swagger API',
    version: '1.0.0',
    description: 'Describing a RESTful API with Swagger',
  },
  host: 'localhost:8000',
  basePath: '/',
  securityDefinitions: {
    JWT: {
      type: 'apiKey',
      description: 'JWT authorization of an API',
      name: 'Authorization',
      in: 'header',
    },
  },
};
Run Code Online (Sandbox Code Playgroud)

但是我无法在 swagger UI 甚至 swagger.json 中获得任何授权

    info: {
       title: "Node Swagger API",
       version: "1.0.0",
       description: "Describing a RESTful API with Swagger"
    },
    host: "localhost:8000",
    basePath: "/",
    securityDefinitions: { },
    swagger: "2.0",
Run Code Online (Sandbox Code Playgroud)

securitydefinitions 块在 swagger.json 文件中仍然是空的,而我已经在 server.js 中添加了 swagger 定义

招摇的用户界面

任何人都可以建议如何启用授权,或者我是否在“安全定义”中错误地使用了模式?

Zac*_*zer 14

为了使这项工作,您需要将openapi属性添加到您的swaggerDefinition对象。

这个 Github issue 中,您可以看到通过添加openapi: 3.0.1,jsdoc 现在将识别安全定义。

const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.1', // YOU NEED THIS
    info: {
      title: 'Your API title',
      version: '1.0.0',
      description: 'Your API description'
    },
    basePath: '/',
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT',
        }
      }
    },
    security: [{
      bearerAuth: []
    }]
  },
  apis: ['/some/path.js|yml'],
};
Run Code Online (Sandbox Code Playgroud)

如果你不希望一个全球性的安全定义,你将需要删除从下面你swaggerDefinition

security: [{
  bearerAuth: []
}]
Run Code Online (Sandbox Code Playgroud)

您现在可以将其添加到各个 API 请求中:

/**
 * @swagger
 * /users:
 *  get:
 *    security:              # <--- ADD THIS
 *      - bearerAuth: []     # <--- ADD THIS
 *    tags:
 *      - Users
 *    description: Returns a single person based on their JWT token
 *    produces:
 *      - application/json
 *    responses:
 *      200:
 *        description: A single person
 *        schema:
 *            $ref: '#/definitions/PersonSimple'
 */
router.get('/users', passport.authenticate('jwt', {session: false}), (req, res, next) => {

    /**
    * Just using the `passport-jwt` middleware as an example here.
    * If the JWT is valid, it attaches the user from the database
    * to the request object
    */
    res.status(200).json({ success: true, user: req.user });
});
Run Code Online (Sandbox Code Playgroud)