使用多个用户池的具有Cognito授权的AWS API Gateway

时间:2020-08-07 10:44:18

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

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

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

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

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

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

2 个答案:

答案 0 :(得分:0)

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

因此,我认为您是对的,因为您需要做一个Lambda授权者,然后承担cognito用户的角色。然后,如果该用户无权执行某项操作,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'],
)

答案 1 :(得分:0)

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

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

  • 允许使用来自不同 aws 帐户的不同 Cognitos 提供的 JWT 对单个端点进行授权。使用 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
相关问题