简体   繁体   中英

Amazon S3: Change bucket policy with Java SDK

I am testing with Amazon S3 compatible Minio using "aws-java-sdk-s3" in Java (Servlet).

Minio wants to set this as "Prefix: *, Read Only" because the initial value of the bucket policy is None.

I added the source code when creating the bucket I wrote as follows, but it did not change.

BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsId, awsKey);
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
    .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
    .withEndpointConfiguration(new EndpointConfiguration(endpoint, null))
    .withPathStyleAccessEnabled(true)
    .build();

s3client.createBucket(new CreateBucketRequest(bucketName));
s3client.setBucketPolicy(bucketName,
    "{"
        + "\"Version\":\"2012-10-17\","
        + "\"Statement\":["
            + "{"
                + "\"Sid\":\"Statement1\","
                + "\"Effect\":\"Allow\","
                + "\"Principal\":\"*\","
                + "\"Action\":[\"s3:GetObject\"],"
                + "\"Resource\":[\"arn:aws:s3:::*\"]"
            + "}"
        + "]"
    + "}"
);

What did I mistake? please tell me. If it is possible to change the initial value of bucket policy for all buckets, such as with Minio's environment setting, there is no problem.

Thank you.

This is how you can get the general public access policy programmatically.

// Gets a public read policy on the bucket.
public static String getPublicReadPolicy(String bucket_name) {
    Policy bucket_policy = new Policy().withStatements(
            new Statement(Statement.Effect.Allow)
                    .withPrincipals(Principal.AllUsers)
                    .withActions(S3Actions.GetObject)
                    .withResources(new Resource(
                            "arn:aws:s3:::" + bucket_name + "/*")));
    return bucket_policy.toJson();
}

Then you can use this policy text to the desired s3 bucket

String policy_text = getPublicReadPolicy(bucket_name);
setBucketPolicy(bucket_name, policy_text);

However in the minio console this will not show with public access. It shows as a custom policy, but it works as public access only.(ref. below image)

在此处输入图像描述

Also this logic can be extended by applying wildcard * instead of specific bucket.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM