我需要能够将以下按钮添加到 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');
})
您使用的是 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: []
对于 Node 项目中的 swagger-ui-express 4.6.3
*注意: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": []
}
]