首页
/ 使用AWS CDK构建带Cognito认证的API Gateway HTTP API与Lambda集成方案

使用AWS CDK构建带Cognito认证的API Gateway HTTP API与Lambda集成方案

2025-07-09 04:53:31作者:卓炯娓

在serverless架构设计中,API Gateway与Lambda的无缝集成是构建现代应用程序的常见模式。本文将以serverless-patterns项目中的实现为例,详细介绍如何使用AWS CDK在TypeScript中构建一个包含Cognito用户认证的API Gateway HTTP API,并实现受保护与未受保护的Lambda函数集成。

架构概览

该解决方案的核心架构包含以下关键组件:

  1. Amazon API Gateway HTTP API:作为前端入口点,提供RESTful接口
  2. AWS Cognito用户池:负责用户身份管理和JWT令牌发放
  3. Lambda函数:包含两种类型
    • 公共Lambda:无需认证即可访问
    • 受保护Lambda:需要有效Cognito JWT令牌才能访问

技术实现细节

1. Cognito用户池配置

首先需要建立用户身份管理系统。通过CDK可以轻松创建Cognito用户池:

const userPool = new cognito.UserPool(this, 'UserPool', {
  selfSignUpEnabled: true,
  autoVerify: { email: true },
  signInAliases: { email: true },
  passwordPolicy: {
    minLength: 8,
    requireLowercase: true,
    requireUppercase: true,
    requireDigits: true,
    requireSymbols: true,
  },
  accountRecovery: cognito.AccountRecovery.EMAIL_ONLY,
});

const userPoolClient = userPool.addClient('UserPoolClient', {
  authFlows: { userPassword: true },
});

2. API Gateway HTTP API创建

HTTP API相比REST API具有更低延迟和成本优势:

const api = new apigw.HttpApi(this, 'HttpApi', {
  description: 'API with Cognito JWT Authorizer',
  corsPreflight: {
    allowOrigins: ['*'],
    allowMethods: [apigw.CorsHttpMethod.ANY],
    allowHeaders: ['*'],
  },
});

3. JWT授权器配置

关键的安全组件,用于验证请求中的JWT令牌:

const authorizer = new apigw.HttpJwtAuthorizer('CognitoAuthorizer', 
  `https://cognito-idp.${region}.amazonaws.com/${userPool.userPoolId}`,
  {
    jwtAudience: [userPoolClient.userPoolClientId],
  }
);

4. Lambda函数实现

示例中包含两个Lambda函数:

公共Lambda(无需认证):

const publicLambda = new lambda.Function(this, 'PublicLambda', {
  runtime: lambda.Runtime.NODEJS_18_X,
  handler: 'index.handler',
  code: lambda.Code.fromAsset('lambda/public'),
});

受保护Lambda(需要认证):

const protectedLambda = new lambda.Function(this, 'ProtectedLambda', {
  runtime: lambda.Runtime.NODEJS_18_X,
  handler: 'index.handler',
  code: lambda.Code.fromAsset('lambda/protected'),
});

5. 路由集成

最后将路由与Lambda函数集成:

api.addRoutes({
  path: '/public',
  methods: [apigw.HttpMethod.GET],
  integration: new apigw.LambdaProxyIntegration({
    handler: publicLambda,
  }),
});

api.addRoutes({
  path: '/protected',
  methods: [apigw.HttpMethod.GET],
  integration: new apigw.LambdaProxyIntegration({
    handler: protectedLambda,
  }),
  authorizer,
});

安全最佳实践

  1. 最小权限原则:确保Lambda函数只拥有执行其任务所需的最小权限
  2. 令牌验证:JWT授权器会自动验证令牌的签名、过期时间和受众
  3. 密码策略:Cognito用户池配置了强密码策略
  4. CORS配置:生产环境应限制允许的源,而非使用通配符

部署与测试

使用CDK部署非常简单:

cdk deploy

部署完成后,可以通过以下方式测试API:

  1. 公共端点:直接通过浏览器或curl访问
  2. 受保护端点
    • 首先通过Cognito获取JWT令牌
    • 然后在请求头中添加Authorization: Bearer <令牌>

扩展思考

此模式可根据实际需求进行多种扩展:

  1. 添加更多授权范围(scopes)实现细粒度权限控制
  2. 集成其他AWS服务如DynamoDB实现完整后端
  3. 添加自定义域名和SSL证书
  4. 实现请求验证和参数转换

这种架构特别适合需要用户认证的现代web和移动应用程序,结合了serverless的弹性优势和Cognito的强大身份管理能力,同时通过CDK实现了基础设施即代码,确保部署的一致性和可重复性。

登录后查看全文
热门项目推荐
相关项目推荐