node.js - 如何使用 JWT 令牌授权 Swagger jsdoc?
问题描述
我已经定义了我的招摇定义,如下所示:
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',
},
},
};
但我无法在 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",
swagger.json 文件中的 securitydefinitions 块仍然为空,而我已经在 server.js 中的 swagger 定义中添加了
谁能建议如何启用授权,或者我是否在“securitydefinitions”中错误地使用了该模式?
解决方案
要完成这项工作,您需要将该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'],
};
如果您不想要全局安全定义,则需要从您的swaggerDefinition
security: [{
bearerAuth: []
}]
您现在可以将其添加到单个 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 });
});