使用无服务器框架的 Cognito 用户池授权方

Cognito user pool authorizer With Serverless Framework

我需要使用 aws cognito 用户池授权我的 API 端点。我可以手动完成,但我需要使用无服务器框架自动化授权部分。

无服务器框架是否支持 aws cognito?

如果是这样,我们如何使用无服务器设置 aws-userpool?

是的。无服务器 (v1.5) 支持 Cognito 用户池授权方。

如果您使用以前版本的无服务器,则必须更新 v1.5 或更高版本。

对于 api 端点的 user-pool 授权,您必须指定池 arn。

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: get
          integration: lambda
          authorizer:
            name: authorizer
            arn: arn:aws:cognito-idp:us-east-1:123456789:userpool/us-east-1_XXXXXX

更多详细信息请阅读 this 文章。

如果您想将授权方设置为您在资源中声明的 Cognito 用户池,您还必须使用 CloudFormation 创建授权方。

functions:
  functionName:
    # ...
    events:
      - http:
          # ...
          authorizer: 
             type: COGNITO_USER_POOLS
             authorizerId: 
               Ref: ApiGatewayAuthorizer

resources:
  Resources:
    ApiGatewayAuthorizer: 
      Type: AWS::ApiGateway::Authorizer
      Properties: 
        Name: CognitoUserPool
        Type: COGNITO_USER_POOLS
        IdentitySource: method.request.header.Authorization
        RestApiId: 
          Ref: ApiGatewayRestApi
        ProviderARNs: 
          - Fn::GetAtt:
              - UserPool
              - Arn

    UserPool:
      Type: AWS::Cognito::UserPool

无服务器 1.35.1

以防有人无意中发现我的做法。这是我的工作解决方案。

无论您在何处创建用户池,都可以继续添加 ApiGatewayAuthorizer

# create a user pool as normal
CognitoUserPoolClient:
  Type: AWS::Cognito::UserPoolClient
  Properties:
    # Generate an app client name based on the stage
    ClientName: ${self:custom.stage}-user-pool-client
    UserPoolId:
      Ref: CognitoUserPool
   ExplicitAuthFlows:
   - ADMIN_NO_SRP_AUTH
   GenerateSecret: true

# then add an authorizer you can reference later
ApiGatewayAuthorizer:
  DependsOn:
  # this is pre-defined by serverless
  - ApiGatewayRestApi
  Type: AWS::ApiGateway::Authorizer
  Properties:
    Name: cognito_auth
    # apparently ApiGatewayRestApi is a global string
    RestApiId: { "Ref" : "ApiGatewayRestApi" }
    IdentitySource: method.request.header.Authorization
    Type: COGNITO_USER_POOLS
    ProviderARNs:
    - Fn::GetAtt: [CognitoUserPool, Arn]

然后当你定义你的函数时

graphql:
  handler: src/app.graphqlHandler
  events:
  - http:
    path: /
    method: post
    cors: true
    integration: lambda
    # add this and just reference the authorizer
    authorizer:
      type: COGNITO_USER_POOLS
      authorizerId:
        Ref: ApiGatewayAuthorizer