CloudFormation 配置 API 网关方法以使用 Cognito Authorizer

the*_*ly2 3 aws-cloudformation amazon-cognito aws-api-gateway

我正在尝试使用 CloudFormation 定义 API Gateway 资源。具体来说,我正在尝试为使用 Cognito 进行身份验证的 API 网关资源方法创建模板。我已经创建了授权者,并且使用控制台我可以毫无问题地执行此配置(请参阅附图)。我只是找不到使用 Cognito 用户池指定 API 方法请求授权的方法。这让我疯狂。据我所知,没有文档涵盖这一点。

有谁知道这是否可能,如果可以,该怎么做?我意识到我可以使用 Swagger 实现这一目标,但我不希望在 Swagger 与 CloudFormation 中重新定义我的所有 API 网关资源。

提前致谢!

控制台方法授权配置

小智 5

如果您使用 SAM,则可以将该池设置为全局默认值,并标记您不想进行身份验证的函数。

  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Cors: "'*'"
      Auth:
        DefaultAuthorizer: MyCognitoAuthorizer
        Authorizers:
          MyCognitoAuthorizer:
            UserPoolArn: !GetAtt MyCognitoUserPool.Arn

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: lambda.handler
      Runtime: nodejs8.10
      Events:
        Root:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: GET

  MyCognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: !Ref CognitoUserPoolName
      Policies:
        PasswordPolicy:
          MinimumLength: 8
      UsernameAttributes:
        - email
      Schema:
        - AttributeDataType: String
          Name: email
          Required: false

  MyCognitoUserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      UserPoolId: !Ref MyCognitoUserPool
      ClientName: !Ref CognitoUserPoolClientName
      GenerateSecret: false
Run Code Online (Sandbox Code Playgroud)

对于您不想落后于 cognito 的功能。在 AWS::Serverless::Function 定义的事件部分中定义。

Events:
        Root:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: GET
            Auth:
              Authorizer: 'NONE'
Run Code Online (Sandbox Code Playgroud)

使用 AWS Sam 模板文档而不是 cloudformation 定义。