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

如何覆盖API Gateway中Amplify授权器并配置Cognito用户池授权器

通过Amplify CLI 自动创建并绑定Cognito User Pool授权器的实现方法

你当前使用的override.ts扩展钩子完全可以实现授权器的自动创建与绑定,不需要手动在控制台重复配置,直接按以下逻辑修改代码即可。


具体实现代码

前提是你的Amplify项目已经通过amplify add auth添加了Cognito认证资源,否则无法获取到User Pool的ARN信息。
直接替换你现有的override文件内容:

// This file is used to override the REST API resources configuration
import { AmplifyApiRestResourceStackTemplate } from '@aws-amplify/cli-extensibility-helper';

export function override(resources: AmplifyApiRestResourceStackTemplate) {
  // 原有CORS头配置逻辑保留
  resources.restApi.body.paths['/storage/{proxy+}'].options['x-amazon-apigateway-integration'].responses.default.responseParameters['method.response.header.Access-Control-Allow-Headers'] = "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,x-aspera-cache-control'";

  // 1. 引用项目中已创建的Cognito User Pool ARN
  // 注意把<YOUR_AUTH_RESOURCE_NAME>替换为amplify/backend/auth目录下的实际文件夹名
  const userPoolArn = resources.addCfnParameter(
    {
      type: "String",
      default: "NONE",
      description: "Cognito User Pool ARN for API authorization",
    },
    "CognitoUserPoolArn",
    {
      "Fn::GetAtt": ["auth<YOUR_AUTH_RESOURCE_NAME>", "Outputs.UserPoolArn"],
    }
  );

  // 2. 在API的OpenAPI定义中注册Cognito授权器
  resources.restApi.body.securityDefinitions = {
    ...(resources.restApi.body.securityDefinitions || {}),
    CognitoAuth: {
      type: "apiKey",
      name: "Authorization",
      in: "header",
      "x-amazon-apigateway-authtype": "cognito_user_pools",
      "x-amazon-apigateway-authorizer": {
        type: "cognito_user_pools",
        providerARNs: [userPoolArn.valueAsString],
      },
    },
  };

  // 3. 给需要鉴权的接口方法绑定授权器,OPTIONS方法跳过(CORS预检不能带鉴权信息)
  const targetPath = resources.restApi.body.paths['/storage/{proxy+}'];
  // 按需调整需要鉴权的HTTP方法
  ['get', 'post', 'put', 'delete', 'patch'].forEach(methodKey => {
    if (targetPath[methodKey]) {
      targetPath[methodKey].security = [{ CognitoAuth: [] }];
    }
  });
}

配置说明

  • 替换auth资源名:代码中<YOUR_AUTH_RESOURCE_NAME>占位符必须替换为实际值,直接打开本地项目的amplify/backend/auth目录,对应文件夹的名称就是要填的值,一般格式为项目名+随机后缀。
  • 多路径适配:如果有多个路径需要绑定授权器,重复第三步的逻辑,遍历对应path下的方法绑定security配置即可,授权器全局只需要定义一次。
  • 不要给OPTIONS方法绑定授权器,否则前端跨域预检请求会被直接拦截,出现跨域错误。
  • 配置完成后执行amplify push,CloudFormation会自动完成授权器创建、端点绑定的全流程,后续API更新时该配置会持久保留,不会被Amplify的默认部署逻辑覆盖。

校验方式

部署完成后进入API Gateway控制台查看,对应API的授权器列表会自动生成你配置的Cognito User Pool授权器,对应接口的方法请求配置中也会自动关联该授权器,不需要手动做任何控制台操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.31 00:06:22