如何为OpenAPI定义安全方案并为API端点应用授权?
为API添加Bearer JWT授权方案
问题说明
需要为API添加安全授权机制,要求指定或所有端点必须通过Bearer JWT令牌验证才能访问,需完成两项核心工作:在OpenAPI中定义并应用安全方案、在Node.js服务中实现实际的令牌验证逻辑。
一、完善OpenAPI安全配置
你已在components/securitySchemes中定义了BearerAuth的JWT授权方案,接下来需将该方案应用到API端点,有两种实现方式:
1. 全局应用(所有端点默认要求授权)
在OpenAPI根节点添加security字段,所有未单独配置的端点都会强制要求Bearer授权:
{ "openapi": "3.0.3", "info": { "description": "NodeJS API documentation of SSV", "version": "1.0.0", "title": "SSV APIs" }, "components": { "securitySchemes": { "BearerAuth": { "name": "Authorization", "in": "header", "type": "apiKey", "scheme": "bearer", "bearerFormat": "JWT", "description": "Enter your bearer token in the format Bearer <token>" } } }, // 新增全局安全规则 "security": [ { "BearerAuth": [] } ] }
2. 单个端点应用(仅指定端点要求授权)
若无需全局强制授权,可在特定接口路径的请求方法中添加security字段,同时支持用security: []标记公开接口:
{ "openapi": "3.0.3", "info": { "description": "NodeJS API documentation of SSV", "version": "1.0.0", "title": "SSV APIs" }, "components": { "securitySchemes": { "BearerAuth": { "name": "Authorization", "in": "header", "type": "apiKey", "scheme": "bearer", "bearerFormat": "JWT", "description": "Enter your bearer token in the format Bearer <token>" } } }, "paths": { "/users": { "get": { "summary": "获取用户列表", "security": [ { "BearerAuth": [] } ], "responses": { "200": { "description": "成功返回用户列表" } } } }, "/public": { "get": { "summary": "公开接口(无需授权)", "security": [], // 明确标记无需授权 "responses": { "200": { "description": "成功返回公开内容" } } } } } }
二、Node.js服务中实现实际授权验证
Swagger UI仅负责生成文档展示,实际的令牌验证需通过中间件实现,推荐使用express-jwt库:
1. 安装依赖
npm install express-jwt
2. 添加授权中间件并集成到路由
修改你的Node.js代码,新增JWT验证逻辑:
import swaggerUi from "swagger-ui-express"; import openapiSpecification from "../swaggerAPI"; import expressJwt from "express-jwt"; const options = { explorer: true, }; // JWT验证中间件 const authenticateJwt = expressJwt({ secret: process.env.JWT_SECRET, // 替换为你的JWT密钥 algorithms: ["HS256"], // 匹配你的JWT签名算法 requestProperty: "user", // 验证成功后,用户信息挂载到req.user上 }); // 方式1:全局应用到所有路由 // app.use(authenticateJwt); // 方式2:仅应用到指定路由 app.get("/users", authenticateJwt, (req, res) => { // 业务逻辑,req.user可获取JWT解析后的用户信息 res.json({ users: [] }); }); // Swagger UI路由(通常设为公开访问) app.use( "/api-docs", swaggerUi.serve, swaggerUi.setup(openapiSpecification, options) );
3. 处理授权错误
添加错误处理中间件捕获JWT验证失败的情况:
app.use((err, req, res, next) => { if (err.name === "UnauthorizedError") { return res.status(401).json({ message: "无效或缺失的授权令牌" }); } next(err); });
内容的提问来源于stack exchange,提问作者Hemanshi Dhrangdhriya
相关产品推荐
相关产品推荐

