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

时间:2017-01-17 22:52:58

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

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

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

提前致谢!

Method Authorization Configuration in Console

2 个答案:

答案 0 :(得分:1)

我没有方便的代码示例,但这是您需要做的事情:

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

答案 1 :(得分: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定义。