You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenAPI 3.0.0下Swagger文档Bearer Token请求头传参异常排查

问题分析与解决方案

第一个接口(/api/v1/mediator/verify/phone/otp)问题

你将components.securitySchemes定义在单个接口的注释内,这会导致Swagger UI无法全局识别该安全方案,进而请求时无法正确传递Authorization头。另外需确认后端日志是否正确读取请求头(HTTP头大小写不敏感,确保代码中读取的头名称正确)。

正确做法是:将securitySchemes全局定义一次,放在所有接口注释的最外层,所有接口通过security字段引用即可。

第二个接口(/api/v1/mediator/verify/email/otp)问题

你同时使用了security: - BearerAuth: []和手动定义Authorization请求头参数,这会触发Swagger UI逻辑冲突——OpenAPI 3.0中,security字段已关联对应安全方案,会自动生成Authorization头的输入控件,手动添加的头参数会干扰该逻辑,导致UI不弹出输入框、参数传递异常。


正确的全局安全方案定义(仅需一次)

/**
 * @swagger
 * components:
 *   securitySchemes:
 *     BearerAuth:
 *       type: http
 *       scheme: bearer
 *       bearerFormat: JWT
 */

第一个接口的修正配置

/**
 * @swagger
 * /api/v1/mediator/verify/phone/otp:
 *   post:
 *     summary: 验证手机OTP
 *     tags: [用户]
 *     security:
 *       - BearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               phone_number:
 *                 type: string
 *                 description: 要验证OTP的手机号码
 *               code:
 *                 type: string
 *                 description: 要验证的OTP验证码
 *     responses:
 *       '200':
 *         description: 手机OTP验证成功
 *       '400':
 *         description: 请求错误 - 验证失败或未提供phone_number/code
 *       '401':
 *         description: 未授权 - 缺失或无效的令牌,此端点需要Bearer令牌授权
 *       '500':
 *         description: 服务器内部错误
 */

第二个接口的修正配置

/**
 * @swagger
 * /api/v1/mediator/verify/email/otp:
 *   post:
 *     summary: 验证邮箱OTP
 *     tags: [用户]
 *     security:
 *       - BearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               email:
 *                 type: string
 *                 description: 要验证OTP的邮箱地址
 *               code:
 *                 type: string
 *                 description: 要验证的OTP验证码
 *     responses:
 *       200:
 *         description: 邮箱OTP验证成功
 *       400:
 *         description: 请求错误 - 验证失败或未提供email/code
 *       401:
 *         description: 未授权 - 无效或缺失令牌
 *       500:
 *         description: 服务器内部错误
 */

额外注意事项

  1. 在Swagger UI中,点击右上角的「Authorize」按钮,输入格式为Bearer {你的令牌}的内容,保存后所有配置了security: - BearerAuth: []的接口都会自动携带该请求头。
  2. 后端代码需正确解析Authorization头:通常要截取Bearer 前缀后的部分作为实际令牌,确保日志能打印解析后的令牌或完整请求头内容。
  3. 确保所有接口的Swagger注释都能正确引用全局定义的BearerAuth安全方案,避免重复定义components。

内容的提问来源于stack exchange,提问作者watch dog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 18:02:49