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

如何在CDK中限制特定Cognito用户组访问API端点?

解决方案

要实现仅Premium用户组访问指定API端点,需结合Cognito用户池授权与API Gateway权限策略,具体步骤如下:

1. 为API Gateway配置Cognito授权器

将端点授权方式从仅API Key改为Cognito用户池授权,让API Gateway验证用户JWT令牌并解析组信息:

// 创建Cognito用户池授权器
const cognitoAuthorizer = new CognitoUserPoolsAuthorizer(this, "CognitoAuthorizer", {
  cognitoUserPools: [userPool],
  authorizerName: "CognitoAuthorizer",
});

// 更新deleteCustomerMetaData端点配置,启用Cognito授权
deleteResourceResource.addMethod(
  "DELETE",
  new LambdaIntegration(userDeleteData),
  { 
    apiKeyRequired: true,
    authorizer: cognitoAuthorizer
  }
);

2. 实现组权限控制(二选一即可)

方式一:API Gateway层面附加IAM策略

直接在API方法上添加策略,仅允许Premium组用户调用:

// 定义Premium组专属访问策略
const premiumOnlyPolicy = new PolicyDocument({
  statements: [
    new PolicyStatement({
      effect: Effect.ALLOW,
      principals: new AnyPrincipal(),
      actions: ["execute-api:Invoke"],
      resources: [deleteResourceResource.methodArn],
      conditions: {
        "StringEquals": {
          "cognito:groups": "Premium"
        }
      }
    })
  ]
});

// 为端点方法绑定该策略
new Policy(this, "PremiumOnlyPolicy", {
  policyName: "PremiumOnlyAccess",
  documents: [premiumOnlyPolicy],
});
方式二:Lambda函数内验证用户组

在业务逻辑层做灵活校验,解析JWT中的组信息判断权限:

// Lambda函数示例(Node.js)
exports.handler = async (event) => {
  // 提取并解析JWT令牌
  const authHeader = event.headers.Authorization;
  if (!authHeader) {
    return { statusCode: 401, body: JSON.stringify({ message: "未提供授权令牌" }) };
  }

  const token = authHeader.split(' ')[1];
  const decoded = require('jsonwebtoken').decode(token);

  // 校验是否属于Premium组
  if (!decoded['cognito:groups'] || !decoded['cognito:groups'].includes('Premium')) {
    return { statusCode: 403, body: JSON.stringify({ message: "无权限访问该端点" }) };
  }

  // 执行删除逻辑
  // ...

  return { statusCode: 200, body: JSON.stringify({ message: "删除成功" }) };
};

3. 确保令牌包含组信息

配置User Pool Client,让Cognito颁发的令牌中包含cognito:groups声明:

const userPoolClient = new UserPoolClient(this, "UserPoolClient", {
  // 保留原有配置
  readAttributes: new ClientAttributes()
    .withStandardAttributes({ email: true })
    .withCustomAttributes("cognito:groups"), // 允许读取组属性
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 15:33:20