如何使用AWS Lambda在AWS S3中为Cognito进行身份验证的用户创建文件夹

时间:2016-06-29 10:52:07

标签: amazon-web-services amazon-s3 lambda amazon-cognito amazon-cognito-facebook

我正在尝试调用lambda函数,该函数为经过身份验证的用户创建AWS资源(S3文件夹和DynamoDB项)。在用户通过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"
      ]
    }
  ]
}

我如何实现这一目标,还是有更好的方法来实现这一目标?

0 个答案:

没有答案