Sample code for 30+ languages & platforms
Java Requires Chilkat v11.6.0+

Amazon S3: Replace a Bucket Policy

See more S3 - REST Examples

Changes access permissions: PUT replaces the entire bucket policy. Retrieve and back up the old policy first, preserve needed statements, and review principals, actions, conditions, and resources. Load the complete JSON policy from a private file. Object ARNs use arn:aws:s3.asp">bucket-name/prefix/*; bucket-level actions use the bucket ARN without a trailing object path.

Requires s3:PutBucketPolicy in the bucket owner account. This example does not grant anonymous access or disable Block Public Access. HTTP 204 confirms success. Policy JSON syntax validation is not a security review.

For general purpose S3 buckets, using regional HTTPS endpoints and AWS Signature Version 4. Directory buckets (S3 Express), access points, Outposts, and other AWS partitions need their own endpoint/authentication rules. Use a bucket name without dots for these virtual-hosted TLS examples; see the path-style example for dotted names.

Provide current IAM credentials in a private qa_data/aws/s3.json file with string fields access_key, secret_key, and session_token for temporary credentials. Prefer short-lived role credentials. This file is explicitly loaded; these examples do not discover profiles or refresh credentials. Keep it outside public content and source control. The session token is included in the signed request. TLS certificate verification is enabled on the Socket used by Rest.

Transport success and HTTP success are different. Keep full diagnostics private; signed requests and presigned URLs can contain credentials or grant access. For retryable reads use bounded backoff with jitter. Before retrying a write with an uncertain outcome, check the resource state. Keep keys, upload IDs, version IDs, ETags, and large sizes as strings.

AWS PutBucketPolicy reference

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.AuthAws;
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Crypt2;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.Rest;
import com.chilkatsoft.chilkat2.Socket;
import com.chilkatsoft.chilkat2.StringBuilder;
import com.chilkatsoft.chilkat2.Xml;

public class ChilkatExample {

    public static void main(String[] args) {
        boolean success = false;

        // StringBuilder compares text by value in every generated language.
        StringBuilder textCompare = new StringBuilder();
        // Assumes Chilkat is unlocked. See Global Unlock Sample.
        success = false;
        // Private configuration, not a file in public web content or source control.
        // Load current IAM credentials authorized for the S3 operation.
        JsonObject credentials = new JsonObject();
        credentials.setStrict(true);
        try {
            credentials.loadFile("qa_data/aws/s3.json");
        } catch (ChilkatException e) {
            System.out.println("Could not load private AWS credentials.");
            return;
        }

        textCompare.clear();
        textCompare.setString(credentials.stringOf("access_key"));
        boolean sameText1 = textCompare.contentsEqual("", true);
        if ((credentials.jsonTypeOf("access_key") != 1) || (sameText1)) {
            System.out.println("Missing or invalid access_key.");
            return;
        }

        textCompare.clear();
        textCompare.setString(credentials.stringOf("secret_key"));
        boolean sameText2 = textCompare.contentsEqual("", true);
        if ((credentials.jsonTypeOf("secret_key") != 1) || (sameText2)) {
            System.out.println("Missing or invalid secret_key.");
            return;
        }

        // General purpose bucket in the commercial AWS partition.
        String region = "us-west-2";
        String bucketName = "amzn-s3-demo-bucket";
        StringBuilder endpoint = new StringBuilder();
        try {
            endpoint.append(bucketName);

            endpoint.append(".");

            endpoint.append("s3.");

            endpoint.append(region);

            endpoint.append(".amazonaws.com");
        } catch (ChilkatException e) {
            System.out.println("Could not build text.");
            return;
        }

        AuthAws aws = new AuthAws();
        aws.setAccessKey(credentials.stringOf("access_key"));
        aws.setSecretKey(credentials.stringOf("secret_key"));
        aws.setRegion(region);
        aws.setServiceName("s3");
        aws.setSignatureVersion(4);
        Rest rest = new Rest();
        rest.setConnectTimeoutMs(20000);
        rest.setIdleTimeoutMs(60000);
        try {
            rest.setAuthAws(aws);
        } catch (ChilkatException e) {
            System.out.println("Could not configure AWS signing.");
            return;
        }

        // Temporary credentials require this token in every signed query.
        // Keep request URLs private. Do not clear this parameter between requests.
        if (credentials.hasMember("session_token")) {
            if (credentials.jsonTypeOf("session_token") != 1) {
                System.out.println("session_token must be a string.");
                return;
            }

            textCompare.clear();
            textCompare.setString(credentials.stringOf("session_token"));
            boolean sameText3 = textCompare.contentsEqual("", true);
            if (!sameText3) {
                try {
                    rest.addQueryParam("X-Amz-Security-Token", credentials.stringOf("session_token"));
                } catch (ChilkatException e) {
                    System.out.println("Could not prepare the request.");
                    return;
                }
            }
        }

        // Connect to the SAME hostname used for TLS verification and request signing.
        Socket connection = new Socket();
        connection.setRequireSslCertVerify(true);
        connection.setMaxReadIdleMs(60000);
        connection.setMaxSendIdleMs(60000);
        try {
            connection.connect(endpoint.getAsString(), 443, true, 20000);
        } catch (ChilkatException e) {
            System.out.println("TLS connection failed; inspect diagnostics privately.");
            return;
        }

        try {
            rest.useConnection(connection, true);
        } catch (ChilkatException e) {
            System.out.println("Could not attach the TLS connection.");
            return;
        }

        Xml xml = new Xml();
        xml.setStrict(true);
        // Load the COMPLETE reviewed policy, including statements to preserve.
        // This operation replaces the existing policy; it does not merge statements.
        JsonObject policy = new JsonObject();
        policy.setStrict(true);
        try {
            policy.loadFile("qa_data/aws/bucket-policy.json");
        } catch (ChilkatException e) {
            System.out.println("Could not load the reviewed bucket policy.");
            return;
        }

        if (!policy.hasMember("Statement")) {
            System.out.println("Policy has no Statement member.");
            return;
        }

        String requestBody = policy.emit();
        try {
            rest.addQueryParam("policy", "");

            rest.addHeader("Content-Type", "application/json");
        } catch (ChilkatException e) {
            System.out.println("Could not prepare the request.");
            return;
        }

        Crypt2 digest = new Crypt2();
        digest.setCharset("utf-8");
        digest.setHashAlgorithm("sha256");
        digest.setEncodingMode("base64");
        String checksumBase64;
        try {
            checksumBase64 = digest.hashStringENC(requestBody);
        } catch (ChilkatException e) {
            System.out.println("Could not calculate the content checksum.");
            return;
        }

        try {
            rest.addHeader("x-amz-checksum-sha256", checksumBase64);
        } catch (ChilkatException e) {
            System.out.println("Could not prepare the request.");
            return;
        }

        String responseBody;
        try {
            responseBody = rest.fullRequestString("PUT", "/", requestBody);
        } catch (ChilkatException e) {
            System.out.println("Request did not complete; inspect diagnostics privately.");
            return;
        }

        if (rest.getResponseStatusCode() != 204) {
            System.out.println("S3 HTTP status: " + rest.getResponseStatusCode());
            try {
                xml.loadXml(responseBody);
                success = true;
            } catch (ChilkatException e) {
                success = false;
            }
            textCompare.clear();
            textCompare.setString(xml.getTag());
            boolean sameText4 = textCompare.contentsEqual("Error", true);
            if ((success) && (sameText4)) {
                System.out.println("S3 error code: " + xml.getChildContent("Code"));
            }

            // Keep signed headers, credentials, URLs, and full diagnostics private.
            // A timeout may leave a write's outcome uncertain. Check before retrying.
            return;
        }

        System.out.println("Bucket policy replaced.");
    }
}