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

如何在受API Key保护的AWS API Gateway中开放C#无服务器应用的/swagger端点

解决方案

要让Lambda中的/swagger端点无需API Key即可访问,你需要在CloudFormation(SAM)模板中单独配置/swagger相关的API资源,覆盖全局的API Key验证要求,具体步骤如下:

1. 修改CloudFormation模板,拆分路径规则

原来的模板用/{proxy+}和/的ANY方法覆盖所有请求,现在需要单独添加/swagger相关路径的事件,设置ApiKeyRequired: false,同时保留原有受保护的路径规则:

"Resources": {
  "AspNetCoreFunction": {
    "Type": "AWS::Serverless::Function",
    "Properties": {
      "Handler": "AWSServerless1::AWSServerless1.LambdaEntryPoint::FunctionHandlerAsync",
      "Runtime": "dotnet6",
      "CodeUri": "",
      "MemorySize": 256,
      "Timeout": 30,
      "Role": null,
      "Policies": ["AWSLambda_FullAccess"],
      "Events": {
        // 保留原有受API Key保护的代理资源
        "ProxyResource": {
          "Type": "Api",
          "Properties": {
            "Path": "/{proxy+}",
            "Method": "ANY",
            "ApiKeyRequired": true
          }
        },
        "RootResource": {
          "Type": "Api",
          "Properties": {
            "Path": "/",
            "Method": "ANY",
            "ApiKeyRequired": true
          }
        },
        // 添加Swagger相关的无API Key验证路径
        "SwaggerIndex": {
          "Type": "Api",
          "Properties": {
            "Path": "/swagger/index.html",
            "Method": "GET",
            "ApiKeyRequired": false
          }
        },
        "SwaggerJson": {
          "Type": "Api",
          "Properties": {
            "Path": "/swagger/v1/swagger.json",
            "Method": "GET",
            "ApiKeyRequired": false
          }
        },
        "SwaggerStaticFiles": {
          "Type": "Api",
          "Properties": {
            "Path": "/swagger/{proxy+}",
            "Method": "GET",
            "ApiKeyRequired": false
          }
        }
      }
    }
  }
}

2. 关键配置说明

  • 原有ProxyResource和RootResource明确设置ApiKeyRequired: true,确保除swagger外的所有请求仍需API Key验证。
  • 添加三个swagger相关事件:
    • /swagger/index.html:对应Swagger UI的主页
    • /swagger/v1/swagger.json:对应API文档的JSON描述文件(注意版本号v1要和你项目中的Swagger配置一致)
    • /swagger/{proxy+}:覆盖Swagger UI依赖的静态资源(如CSS、JS文件)
  • 所有swagger相关路径的ApiKeyRequired设为false,允许浏览器直接访问。

3. 额外注意事项

  • 如果你的Swagger配置使用了其他版本号(比如v2),需要对应修改/swagger/v1/swagger.json中的版本路径。
  • 部署修改后的模板后,需要重新发布API Gateway的部署阶段,确保配置生效。
  • 若之前API Gateway是全局启用API Key,资源级别的ApiKeyRequired设置优先级更高,会自动覆盖全局规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 11:25:17