aws-api-gateway - CloudFormation 配置 API 网关方法以使用 Cognito Authorizer

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

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

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

提前致谢!

Method Authorization Configuration in Console

最佳答案

如果您使用 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 定义。

关于aws-api-gateway - CloudFormation 配置 API 网关方法以使用 Cognito Authorizer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41708481/

相关文章:

amazon-web-services - 使用 Lambda、API Gateway 和 Cloudfront 时,尽管在 Lambda 响应中指定了 'Access-Control-Allow-Origin',但 CORS 错误

amazon-web-services - 如何触发step函数并获取失败或成功状态

amazon-web-services - 经过身份验证登录后,AWS Cognito NotAuthorizedException "Invalid Access Token"错误

Android,Cognito : can sign in, 但无法进行经过身份验证的 AWS 调用

amazon-web-services - ID 为 X 的堆栈不存在或已被删除 - cfn-init

amazon-web-services - AWS : When setting IAM permissions for users/groups, 我是否需要授予云形成模板中使用的服务的所有权限?

node.js - DynamoDb 扫描返回本地而非实时的所有数据

node.js - 从另一个 lambda 调用 lambda 时出现问题

aws-lambda - 如何为自定义 GatewayAPI 域的 Route53 别名记录创建 SAM 模板 block

amazon-web-services - Cloudformation Cognito - 如何通过 SAM 模板设置应用程序客户端设置、域和联合身份