2

我正在尝试调用为经过身份验证的用户创建 AWS 资源(S3 文件夹和 DynamoDB 项)的 lambda 函数。用户通过 AWS Cognito 登录后,将从客户端调用 Lambda 函数。

从客户端发出 S3 putObject 请求可以正常工作。但是,如果我从调用的 Lambda 函数发出相同的请求,它就会失败。

Client --> S3 --> Works
Client --> Lambda --> S3 --> Does not work

这是我的 Lambda 函数:

s3 = boto3.resource('s3')
bucket = s3.Bucket('BUCKET_NAME')
id = str(context.identity.cognito_identity_id)
bucket.put_object(Key='cognito/users/{}/'.format(id))

我收到以下错误

ClientError: An error occurred (AccessDenied) when calling the PutObject operation: 
Access Denied

Cognito Authenticated Role 和 Lambda Role 都指向同一个角色:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": ["lambda:InvokeFunction"],
            "Effect": "Allow",
            "Resource": "arn:aws:lambda:us-east-1:ACCOUNT_ID:function:CreateResources"
        },
        {
            "Effect": "Allow",
            "Action": ["s3:ListBucket"],
            "Resource": ["arn:aws:s3:::BUCKET_NAME"],
            "Condition": {
                "StringLike": {
                    "s3:prefix": ["cognito/users/${cognito-identity.amazonaws.com:sub}/*"]
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject",
                "s3:DeleteObject"
            ],
            "Resource": [
                "arn:aws:s3:::BUCKET_NAME/cognito/users/${cognito-identity.amazonaws.com:sub}",
                "arn:aws:s3:::BUCKET_NAME/cognito/users/${cognito-identity.amazonaws.com:sub}/*"
            ]
        }
    ]
}

和信任关系:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "cognito-identity.amazonaws.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "cognito-identity.amazonaws.com:aud": "us-east-1:IDENTITY_POOL_ID"
        },
        "ForAnyValue:StringLike": {
          "cognito-identity.amazonaws.com:amr": "authenticated"
        }
      }
    },
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": [
        "sts:AssumeRole",
        "sts:AssumeRoleWithWebIdentity"
      ]
    }
  ]
}

我怎样才能做到这一点,或者有更好的方法来做到这一点?

4

0 回答 0