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

如何在OpenAPI YAML文件中为API请求头添加Bearer密钥

基于OpenAPI 3.0实现Bearer认证的正确方式

你的OpenAPI定义框架没问题,但存在几处格式和细节问题,调整后即可正确实现请求头的Authorization认证,以下是修正后的完整配置及关键说明:

修正后的完整YAML配置

openapi: 3.0.0
info:
  title: Endpoints 
  version: 1.0.0
servers:
  - url: http://localhost:8080  # 补充协议前缀,确保地址合法
security:
  - bearerAuth: []  # 全局默认启用Bearer认证,所有接口都会要求携带令牌
paths:
  /notification:  # 修正路径格式,避免空格
    post:  # 修正缩进,与上级路径对齐
      tags:
        - Notification
      security: 
        - bearerAuth: []  # 显式指定该接口需要认证(可省略,继承全局配置)
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/definedschema'
components:
  securitySchemes:
    bearerAuth: 
      type: http
      scheme: bearer
      bearerFormat: JWT  # 指明令牌为JWT格式,辅助工具识别
  schemas:
    definedschema:  # 补充实际的Schema定义,这里仅做示例
      type: object
      properties:
        message:
          type: string

关键配置说明

  • 路径格式修正:API路径不能包含空格,需改为合法的路径名(如/notification)
  • 缩进规范:YAML对缩进敏感,post方法必须与对应的路径节点对齐,否则解析会报错
  • 全局与接口级认证:根节点的security会为所有接口默认开启认证;若某接口不需要认证,可在该接口下设置security: []来覆盖全局配置
  • 认证头要求:客户端调用接口时,需在请求头中携带Authorization: Bearer <你的JWT令牌>,此配置会让Swagger UI、Postman等工具自动生成对应的认证输入选项,方便测试
  • Schema补充:components/schemas下需补充实际的请求体Schema定义,否则无法正确校验请求格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 08:24:52