在PutObject时设置s3存储桶策略

时间:2018-10-28 13:55:45

标签: java amazon-web-services amazon-s3

public String getPolicy() throws Exception {
        String policy_document = "{\"expiration\": \"2020-01-01T00:00:00Z\",\n" +
                "  \"conditions\": [ \n" +
                "    {\"bucket\": \"bucket\"}, \n" +
                "    [\"starts-with\", \"$Content-Type\", \"image/\"],\n" +
                "    [\"content-length-range\", 0, 100]\n" +
                "  ]\n" +
                "}";
        String aws_secret_key = "xxxxx";
        String policy = (new BASE64Encoder()).encode(policy_document.getBytes("UTF-8"))
                .replaceAll("\n", "").replaceAll("\r", "");

        Mac hmac = Mac.getInstance("HmacSHA1");
        hmac.init(new SecretKeySpec(
                aws_secret_key.getBytes("UTF-8"), "HmacSHA1"));
        String signature = (new BASE64Encoder()).encode(
                hmac.doFinal(policy.getBytes("UTF-8")))
                .replaceAll("\n", "");

        return policy;
    }

上传时-

   ObjectMetadata objectMetadata = new ObjectMetadata();
   objectMetadata.setHeader("policy", getPolicy());

   s3Client.putObject(bucket, key, inputStream, objectMetadata);

我们可以像上面那样传递策略头来拒绝违反策略条件的s3 putObject请求吗?

我认为可以通过s3Client.setBucketPolicy,但是有没有办法为每个放置请求设置这些策略?

0 个答案:

没有答案