【问题标题】:AWS API Gateway with Cognito Authorization using multiple user pools使用多个用户池的具有 Cognito 授权的 AWS API 网关
【发布时间】:2020-11-27 16:44:08
【问题描述】:

我有多个 Cognito 用户池,用于将不同应用程序的用户分开。我还有一组在 API Gateway 中定义的 API。这些 API 很常见,多个应用程序可以使用它们。我正在尝试使用 Cognito 资源服务器和自定义范围来控制哪些应用程序可以访问哪些 API。

这是我一直关注的指南:https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html

我遇到的问题是我必须在创建 API Gateway 授权方时指定用户池。我可以创建多个授权者,但在将授权者附加到 API 网关方法时,我似乎只能选择一个。

此设置意味着在使用 Cognito 授权方时,只有一个用户池可以访问 API Gateway 中的 API。这是正确的还是我错过了什么?

我唯一的选择似乎是使用 Lambda 授权者并手动完成所有这些操作。但是,这意味着我必须存储 API 端点/方法和自定义范围之间的映射。如果我采用这种方法,我将如何验证访问令牌是否可以访问传入请求中的端点?

【问题讨论】:

    标签: amazon-web-services aws-api-gateway amazon-cognito


    【解决方案1】:

    我做过类似的事情,但不完全是你正在做的事情,但也许它会引导你朝着正确的方向前进。

    所以我认为你是对的,你需要做一个 Lambda 授权方,然后承担认知用户的角色。然后,如果该用户无权执行某项操作,IAM 就会将其炸毁。

    client = boto3.client('sts')
    role=event['requestContext']['authorizer']['claims']['cognito:preferred_role']
    
    assumed_role_object = client.assume_role(
        RoleArn=role,
        RoleSessionName='APIrole'
    )
    credentials=assumed_role_object['Credentials']
    dynamo_resource=boto3.resource(
        'dynamodb',
        aws_access_key_id=credentials['AccessKeyId'],
        aws_secret_access_key=credentials['SecretAccessKey'],
        aws_session_token=credentials['SessionToken'],
    )
    

    【讨论】:

      【解决方案2】:

      这里发布了一个解决方案: How to use multiple Cognito user pools for a single endpoint with AWS API Gateway?

      我发现 Abhay Nayak 的回答很有用,它帮助我实现了我的场景:

      • 允许使用不同 Cognitos 提供的 JWT 从不同的 aws 帐户对单个端点进行授权。使用 cognito 用户池授权器,而不是自定义 lambda 授权器。

      这是我的无服务器 .yml 模板中的授权方和端点:

      functions:
        service:
          handler: service.service
          events:
            - http:
                path: service
                method: get
                authorizer:
                  type: COGNITO_USER_POOLS
                  authorizerId:
                    Ref: ApiGatewayAuthorizer
      
      
      resources:
        Resources:
          ApiGatewayAuthorizer:
            Type: AWS::ApiGateway::Authorizer
            Properties:
              AuthorizerResultTtlInSeconds: 300
              Name: API_AUTH_cognito_authorizer
              IdentitySource: method.request.header.Authorization
              RestApiId:
                Ref: ApiGatewayRestApi
              Type: COGNITO_USER_POOLS
              ProviderARNs:
                - arn:aws:cognito-idp:us-east-1:account1:userpool/userpool1
                - arn:aws:cognito-idp:us-east-1:account1:userpool/userpool2
                - arn:aws:cognito-idp:us-east-1:account2:userpool/userpool3
                - arn:aws:cognito-idp:us-east-1:account2:userpool/userpool4
      

      【讨论】:

        猜你喜欢
        • 2018-01-24
        • 2017-09-04
        • 2017-10-25
        • 2018-11-19
        • 2021-10-08
        • 2020-03-31
        • 2018-01-12
        • 2019-11-18
        • 2019-11-07
        相关资源
        最近更新 更多