如何在Serverless.yml中为Lambda配置Resources内的Cognito用户池授权器
在Serverless框架中为Lambda配置Cognito User Pool授权器
没问题,我来帮你搞定这个配置!你猜的方向没错,但不需要手动硬编码ARN,Serverless框架可以通过CloudFormation的引用自动获取用户池的ARN,而且配置方式有规范的写法,我给你一步步拆解:
1. 先在Resources部分声明Cognito User Pool
首先你需要在serverless.yml的Resources块里定义你的Cognito用户池,以及对应的用户池客户端(用于用户登录获取token)。示例如下:
resources: Resources: # 定义Cognito User Pool MyCognitoUserPool: Type: AWS::Cognito::UserPool Properties: UserPoolName: MyAppUserPool Schema: - Name: email AttributeDataType: String Mutable: false Required: true Policies: PasswordPolicy: MinimumLength: 8 RequireUppercase: true RequireLowercase: true RequireNumbers: true # 定义Cognito User Pool Client MyCognitoUserPoolClient: Type: AWS::Cognito::UserPoolClient Properties: ClientName: MyAppUserPoolClient UserPoolId: !Ref MyCognitoUserPool GenerateSecret: false # 前端应用一般设为false ExplicitAuthFlows: - ALLOW_USER_PASSWORD_AUTH - ALLOW_REFRESH_TOKEN_AUTH
2. 为Lambda函数配置Cognito授权器
接下来在你的Lambda函数的events配置里(假设是API Gateway触发的函数),添加authorizer字段,指定使用Cognito用户池作为授权器:
functions: myProtectedFunction: handler: src/handler.main events: - http: path: /my-protected-endpoint method: get authorizer: type: COGNITO_USER_POOLS # 两种引用方式二选一即可 providerARNs: - !Ref MyCognitoUserPool # 自动获取用户池ARN # 或者用authorizerId的方式 # authorizerId: # Ref: MyCognitoUserPool
关键说明
- 如何获取用户池ARN?:不需要手动复制ARN,用CloudFormation的
!Ref函数引用你定义的用户池资源(比如上面的MyCognitoUserPool),Serverless框架会自动解析成对应的ARN。如果某些场景需要明确获取ARN,也可以用!GetAtt MyCognitoUserPool.Arn。 - 授权器类型:必须指定
type: COGNITO_USER_POOLS,这和aws_iam类型的授权器区分开,前者专门用于验证Cognito签发的JWT token。 - 测试验证:调用接口时需要在请求头里带上
Authorization: Bearer <你的Cognito JWT Token>,API Gateway会自动验证token的有效性,只有合法的请求才会触发Lambda函数。
完整示例整合
把上面的部分整合到一个完整的serverless.yml里,大概是这样:
service: my-serverless-app frameworkVersion: '3' provider: name: aws runtime: nodejs18.x region: us-east-1 # 确保和Cognito用户池区域一致 functions: myProtectedFunction: handler: src/handler.main events: - http: path: /my-protected-endpoint method: get authorizer: type: COGNITO_USER_POOLS providerARNs: - !Ref MyCognitoUserPool resources: Resources: MyCognitoUserPool: Type: AWS::Cognito::UserPool Properties: UserPoolName: MyAppUserPool Schema: - Name: email AttributeDataType: String Mutable: false Required: true Policies: PasswordPolicy: MinimumLength: 8 RequireUppercase: true RequireLowercase: true RequireNumbers: true MyCognitoUserPoolClient: Type: AWS::Cognito::UserPoolClient Properties: ClientName: MyAppUserPoolClient UserPoolId: !Ref MyCognitoUserPool GenerateSecret: false ExplicitAuthFlows: - ALLOW_USER_PASSWORD_AUTH - ALLOW_REFRESH_TOKEN_AUTH
这样配置后,你的Lambda接口就会被Cognito用户池保护起来,只有持有有效JWT token的请求才能访问。
内容的提问来源于stack exchange,提问作者Resist Design
相关产品推荐
相关产品推荐

