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

CloudFormation部署API Gateway时OpenAPI中Cognito授权器ARN如何动态传入

根因说明

API Gateway 导入OpenAPI规范时会直接解析components.securitySchemes下的配置完成授权器初始化,该过程发生在阶段变量生效之前,因此阶段变量无法作用于该字段,这是此前尝试阶段变量不生效的核心原因。

可行解决方案

方案1:OpenAPI文件预替换(通用无依赖)

适合OpenAPI文件独立维护、不想耦合CloudFormation语法的场景:

  • 在openapi-spec.yaml中将providerARNs的硬编码值替换为自定义占位符,例如{{COGNITO_USER_POOL_ARN}}
  • 部署CloudFormation栈前,通过CI/CD流水线或本地部署脚本执行变量替换:根据当前部署的账号/环境,拉取对应Cognito用户池的ARN替换占位符
  • 将替换完成的OpenAPI文件上传到指定S3路径,再通过CloudFormation的BodyS3Location引入即可

方案2:使用CloudFormation AWS::Include 宏直接注入动态值

不想额外维护替换脚本的场景可使用CloudFormation内置宏处理,支持直接识别CloudFormation内置函数:

  1. 修改openapi-spec.yaml中的providerARNs配置,使用!Sub语法引用参数:
components:
  securitySchemes:
    CognitoAuth:
      type: apiKey
      name: Authorization
      in: header
      x-amazon-apigateway-authtype: cognito_user_pools
      x-amazon-apigateway-authorizer:
        type: cognito_user_pools
        providerARNs:
          - !Sub ${CognitoUserPoolArn}
  1. 修改CloudFormation模板中RestApi资源配置,将原BodyS3Location改为用AWS::Include宏引入S3文件:
Resources:
  MyRestApi:
    Type: AWS::ApiGateway::RestApi
    Properties:
      Name: MyBusinessApi
      Body:
        Fn::Transform:
          Name: AWS::Include
          Parameters:
            Location: s3://<你的S3桶路径>/openapi-spec.yaml
Parameters:
  CognitoUserPoolArn:
    Type: String
    Description: 当前环境对应的Cognito用户池ARN
  1. 部署CloudFormation栈时,直接传入对应环境的CognitoUserPoolArn参数值即可,CloudFormation会自动完成变量注入。

方案3:授权器配置完全与OpenAPI解耦

如果希望OpenAPI文件完全不包含云厂商相关的扩展配置,可单独在CloudFormation中声明授权器资源:

  • 移除OpenAPI文件中components.securitySchemes下的Cognito授权器定义
  • 在CloudFormation模板中新增AWS::ApiGateway::Authorizer资源:
MyCognitoAuthorizer:
  Type: AWS::ApiGateway::Authorizer
  Properties:
    Name: CognitoUserPoolAuthorizer
    RestApiId: !Ref MyRestApi
    Type: COGNITO_USER_POOLS
    ProviderARNs:
      - !Ref CognitoUserPoolArn
    IdentitySource: method.request.header.Authorization
  • 在OpenAPI对应接口方法上通过扩展字段指定该授权器,或直接在CloudFormation的AWS::ApiGateway::Method资源中关联授权器即可。

内容的提问来源于stack exchange,提问作者Hagalín Ásgrímur Guðmundsson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:48:02