【问题标题】:CloudFormation to Configure API Gateway Method to use Cognito AuthorizerCloudFormation 配置 API 网关方法以使用 Cognito Authorizer
【发布时间】:2017-06-02 04:27:41
【问题描述】:

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

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

提前致谢!

【问题讨论】:

    标签: aws-api-gateway amazon-cognito amazon-cloudformation


    【解决方案1】:

    如果您使用的是 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
    

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

    Events:
            Root:
              Type: Api
              Properties:
                RestApiId: !Ref MyApi
                Path: /
                Method: GET
                Auth:
                  Authorizer: 'NONE'
    

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

    【讨论】:

      【解决方案2】:

      我手头没有代码示例,但您需要这样做:

      1) 将Authorizer 资源添加到您的模板,类型为“COGNITO_USER_POOLS”,

      2) 将 API method 资源上的 authorizerId 设置为来自授权方的 ID 引用。将方法上的 authorizationType 设置为“COGNITO_USER_POOLS”

      至于用户池本身,您将需要使用自定义资源,至少在官方支持发布之前是这样。您可以使用多种开源实现(这里有一个示例:https://github.com/aws-samples/aws-api-gateway-developer-portal/tree/7d0d1e56d54e9775ee2d18907ebdf1db9dafcc06/lambdas/cognito-cloudformation-custom-resource

      【讨论】:

      • 非常感谢您的帮助。我很确定这正是我所需要的。在我将其标记为正确之前进行一些测试。
      猜你喜欢
      • 1970-01-01
      • 2019-06-24
      • 2021-02-02
      • 1970-01-01
      • 2019-08-20
      • 1970-01-01
      • 2018-05-17
      • 2021-10-18
      • 2022-10-20
      相关资源
      最近更新 更多