gpt4 book ai didi

node.js - 如何使用 JWT token 授权 Swagger jsdoc?

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:28 27 4
gpt4 key购买 nike

我已经定义了我的 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',
},
},
};

但是我无法在 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 block 仍然为空,而我已经在 server.js 中添加了 swagger 定义

Swagger UI

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

最佳答案

要实现此功能,您需要将 openapi 属性添加到 swaggerDefinition 对象中。

this 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 });
});

关于node.js - 如何使用 JWT token 授权 Swagger jsdoc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50736784/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com