首页 > 解决方案 > S3 写入访问被拒绝 - 存储桶需要不同的策略

问题描述

当我尝试从本地开发机器上传到新创建的 S3 存储桶“dev-image”时,出现写入访问错误。我发现我可以(并且已经能够)从本地运行的应用程序上传到 S3 prod“图像”存储桶,但无法从同一环境上传到“开发图像”。阻止所有公共访问已关闭,存储桶所有者可以列出和写入两个存储桶的对象。我必须专门向“dev-image”存储桶添加一个策略以允许写访问(PutObject)。这两个桶一定有什么不同,但我看不到。任何想法在哪里看?

这些是 AWS S3 上的策略:

dev-image:

{
    "Version": "2012-10-17",
    "Id": "Policy1606066621241",
    "Statement": [
        {
            "Sid": "Allow all read",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::dev-image/*"
        },
        {
            "Sid": "Allow write from dev machine",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:PutObject",
            "Resource": "arn:aws:s3:::dev-image/*",
             }
        }
    ]
}

image:

{
    "Version": "2012-10-17",
    "Id": "Policy1445028673753",
    "Statement": [
        {
            "Sid": "Allow all read",
            "Effect": "Allow",
            "Principal": "*",
            "Action": "s3:GetObject",
            "Resource": "arn:aws:s3:::image/*"
        } 
   ]
}

这是表单代码:

<form class="form-horizontal" name="s3Form" action=<%= s3FormAction %> method="post" enctype="multipart/form-data">

    <fieldset>

        <input type="hidden" name="key" value="<%= imageFileName %>">
        <input type="hidden" name="AWSAccessKeyId" value="<%= S3AccessKeyId %>"> 
        <input type="hidden" name="acl" value="private"> 
        <input type="hidden" name="success_action_redirect" value="<%= s3SuccessAction %>">
        <input type="hidden" name="policy" value="<%= encPolicy %>" >
        <input type="hidden" name="signature" value="<%= signature %>" >
        <input type="hidden" name="Content-Type" value="image/jpeg">

这是我用来编码 S3 策略的代码:

public static String encodeS3Policy(String s3SuccessAction, String bucket) throws Exception
    {
        String policy =
            "{\"expiration\": \"2040-01-01T00:00:00Z\"," +
              "\"conditions\": [" +
                (bucket==null || bucket.length()==0 ? "" : "{\"bucket\": \"" + bucket + "\"}," ) +
                "[\"starts-with\", \"$key\", \"\"]," +
                "{\"acl\": \"private\"}," +
                "{\"success_action_redirect\": \"" + s3SuccessAction + "\"}," +
                "[\"starts-with\", \"$Content-Type\", \"\"]," +
                "[\"content-length-range\", 0, 10485760]" +                                 // 10 MB max file up load
                "]" +
            "}";

        policy.replaceAll("\n","").replaceAll("\r","");


        // Encode the policy
        String encPolicy = Base64.getEncoder().encodeToString(policy.getBytes("UTF-8"));

        return encPolicy;
    }

标签: amazon-s3acl

解决方案


推荐阅读