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

跨AWS账号使用CDK创建Cognito UserPool授权器的方法

跨AWS账号Cognito用户池的API Gateway授权器创建方法

当Cognito用户池与API Gateway分属不同AWS账号时,无法直接通过导入IUserPool对象的方式创建CognitoUserPoolsAuthorizer,可以通过以下方式解决:

1. 直接使用用户池ARN创建授权器

绕过IUserPool对象的依赖,直接指定跨账号用户池的ARN来构造授权器。以AWS CDK为例:

import * as apigateway from 'aws-cdk-lib/aws-apigateway';
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';

export class ApiGatewayStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    // 替换为跨账号Cognito用户池的ARN
    const crossAccountUserPoolArn = 'arn:aws:cognito-idp:us-east-1:123456789012:userpool/us-east-1_XXXXXXXXX';

    // 创建跨账号用户池授权器
    const crossAccountAuthorizer = new apigateway.CognitoUserPoolsAuthorizer(this, 'CrossAccountAuthorizer', {
      authorizerName: 'CrossAccountUserPoolAuth',
      userPoolArns: [crossAccountUserPoolArn], // 直接传入ARN数组
    });

    // 创建API并绑定授权器
    const api = new apigateway.RestApi(this, 'CrossAccountAuthApi');
    const testResource = api.root.addResource('test');
    testResource.addMethod('GET', new apigateway.HttpIntegration('https://example.com'), {
      authorizer: crossAccountAuthorizer,
      authorizationType: apigateway.AuthorizationType.COGNITO,
    });
  }
}

2. 配置跨账号权限

API Gateway所在账号需要具备访问跨账号Cognito用户池的权限,需在用户池所在账号做以下配置:

方式一:添加用户池资源策略

在跨账号Cognito用户池的资源策略中,允许API Gateway所在账号访问必要的Cognito API:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::API_GATEWAY_ACCOUNT_ID:root"
      },
      "Action": [
        "cognito-idp:DescribeUserPool",
        "cognito-idp:GetUserPoolClient"
      ],
      "Resource": "arn:aws:cognito-idp:REGION:USER_POOL_ACCOUNT_ID:userpool/USER_POOL_ID"
    }
  ]
}

方式二:给API Gateway执行角色附加权限

如果API Gateway使用了自定义执行角色,可在该角色的权限策略中添加允许访问跨账号用户池的语句:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "cognito-idp:DescribeUserPool",
        "cognito-idp:GetUserPoolClient"
      ],
      "Resource": "arn:aws:cognito-idp:REGION:USER_POOL_ACCOUNT_ID:userpool/USER_POOL_ID"
    }
  ]
}

3. 验证令牌有效性

API Gateway会使用跨账号用户池的公钥来验证JWT令牌的有效性,无需额外配置密钥同步,AWS会自动处理跨账号的公钥获取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:12:50