Bucket ACL

更新时间:
复制 MD 格式

A bucket ACL (access control list) controls bucket-level access in OSS by setting a bucket to public or private. Objects uploaded without a specified ACL inherit the bucket ACL.

How it works

Bucket ACLs use predefined values to control bucket access.

Value

Description

private (default)

Private. Only the bucket owner or authorized users can read and write objects in the bucket.

public-read

Public read. Only the bucket owner or authorized users can write objects, but anyone, including anonymous users, can read them.

public-read-write

Public read/write. Anyone, including anonymous users, can read and write objects in the bucket.

Important
  • public-read-write: Allows anyone on the internet to read and write objects in the bucket, which may cause data exposure, unexpected charges, or malicious uploads. Avoid unless specifically required.

  • public-read: Allows anyone on the internet to read objects in the bucket, which may cause data exposure and unexpected charges. Use with caution.

Set a bucket ACL

When you create a bucket, Block Public Access is enabled by default and the ACL is set to private. To use public-read or public-read-write, disable Block Public Access first.

Console

  1. Go to the Buckets list and click the target bucket.

  2. In the left-side navigation pane, choose Permission Control > ACL (Access Control List).

  3. Click Configure and modify the bucket ACL as needed.

  4. Click Save.

ossutil CLI

Run the put-bucket-acl command in ossutil 2.0 to set the bucket ACL.

ossutil api put-bucket-acl --bucket example-bucket --acl private

SDK

The following samples show how to set a bucket ACL with common SDKs. Additional SDK samples are available in the SDK reference.

// This sample code shows how to set the access control list (ACL) for a bucket.
// Before you run the sample code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

import com.aliyun.sdk.service.oss2.OSSClient;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.StaticCredentialsProvider;
import com.aliyun.sdk.service.oss2.models.*;

public class SetBucketAcl {

    public static void main(String[] args) {
        String bucketName = "example-bucket";

        String accessKeyId = System.getenv("OSS_ACCESS_KEY_ID");
        String accessKeySecret = System.getenv("OSS_ACCESS_KEY_SECRET");
        CredentialsProvider provider = new StaticCredentialsProvider(accessKeyId, accessKeySecret);

        try (OSSClient client = OSSClient.newBuilder()
                .credentialsProvider(provider)
                .region("<region-id>")
                .build()) {

            // Set the bucket ACL to private.
            // Valid values: "private", "public-read", and "public-read-write".
            PutBucketAclRequest putRequest = PutBucketAclRequest.newBuilder()
                    .bucket(bucketName)
                    .acl("private")
                    .build();
            PutBucketAclResult putResult = client.putBucketAcl(putRequest);
            System.out.println("Bucket ACL set successfully. RequestId: " + putResult.requestId());

            // Get the bucket ACL.
            GetBucketAclRequest getRequest = GetBucketAclRequest.newBuilder()
                    .bucket(bucketName)
                    .build();
            GetBucketAclResult getResult = client.getBucketAcl(getRequest);
            System.out.println("Current bucket ACL: " + getResult.accessControlPolicy().accessControlList().grant());

        } catch (Exception e) {
            System.err.println("Operation failed: " + e.getMessage());
        }
    }
}
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This sample code shows how to set the access control list (ACL) for a bucket.
# Before you run the sample code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

import alibabacloud_oss_v2 as oss


def main() -> None:
    bucket_name = "example-bucket"

    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
    cfg = oss.config.load_default()
    cfg.credentials_provider = credentials_provider
    cfg.region = "<region-id>"

    client = oss.Client(cfg)

    # Set the bucket ACL to private.
    # Valid values: "private", "public-read", and "public-read-write".
    put_result = client.put_bucket_acl(oss.PutBucketAclRequest(
        bucket=bucket_name,
        acl="private"
    ))
    print(f"Bucket ACL set successfully. RequestId: {put_result.request_id}")

    # Get the bucket ACL.
    get_result = client.get_bucket_acl(oss.GetBucketAclRequest(
        bucket=bucket_name
    ))
    print(f"Current bucket ACL: {get_result.acl}")


if __name__ == "__main__":
    main()
// This sample code shows how to set the access control list (ACL) for a bucket.
// Before you run the sample code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

package main

import (
	"context"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

func main() {
	bucketName := "example-bucket"

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion("<region-id>")

	client := oss.NewClient(cfg)

	// Set the bucket ACL to private.
	// Valid values: oss.BucketACLPrivate, oss.BucketACLPublicRead, and oss.BucketACLPublicReadWrite.
	putResult, err := client.PutBucketAcl(context.TODO(), &oss.PutBucketAclRequest{
		Bucket: oss.Ptr(bucketName),
		Acl:    oss.BucketACLPrivate,
	})
	if err != nil {
		log.Fatalf("Failed to set bucket ACL: %v", err)
	}
	log.Printf("Bucket ACL set successfully. RequestId: %s", putResult.Headers.Get("X-Oss-Request-Id"))

	// Get the bucket ACL.
	getResult, err := client.GetBucketAcl(context.TODO(), &oss.GetBucketAclRequest{
		Bucket: oss.Ptr(bucketName),
	})
	if err != nil {
		log.Fatalf("Failed to get bucket ACL: %v", err)
	}
	log.Printf("Current bucket ACL: %s", *getResult.ACL)
}
<?php
// This sample code shows how to set the access control list (ACL) for a bucket.
// Before you run the sample code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

require_once __DIR__ . '/vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

$bucketName = 'example-bucket';

$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion('<region-id>');

$client = new Oss\Client($cfg);

try {
    // Set the bucket ACL to private.
    // Valid values: BucketACLType::PRIVATE, BucketACLType::PUBLIC_READ, and BucketACLType::PUBLIC_READ_WRITE.
    $putResult = $client->putBucketAcl(new Oss\Models\PutBucketAclRequest(
        bucket: $bucketName,
        acl: Oss\Models\BucketACLType::PRIVATE
    ));
    printf("Bucket ACL set successfully. RequestId: %s\n", $putResult->requestId);

    // Get the bucket ACL.
    $getResult = $client->getBucketAcl(new Oss\Models\GetBucketAclRequest(
        bucket: $bucketName
    ));
    printf("Current bucket ACL: %s\n", $getResult->accessControlList->grant);
} catch (Exception $e) {
    printf("Operation failed: %s\n", $e->getMessage());
}
// This sample code shows how to set the access control list (ACL) for a bucket.
// Before you run the sample code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

using OSS = AlibabaCloud.OSS.V2;

var bucketName = "example-bucket";
var region = "<region-id>";

var cfg = OSS.Configuration.LoadDefault();
cfg.CredentialsProvider = new OSS.Credentials.EnvironmentVariableCredentialsProvider();
cfg.Region = region;

using var client = new OSS.Client(cfg);

try
{
    // Set the bucket ACL to private.
    // Valid values: "private", "public-read", and "public-read-write".
    var putResult = await client.PutBucketAclAsync(new OSS.Models.PutBucketAclRequest()
    {
        Bucket = bucketName,
        Acl = "private"
    });
    Console.WriteLine($"Bucket ACL set successfully. RequestId: {putResult.RequestId}");

    // Get the bucket ACL.
    var getResult = await client.GetBucketAclAsync(new OSS.Models.GetBucketAclRequest()
    {
        Bucket = bucketName
    });
    Console.WriteLine($"Current bucket ACL: {getResult.AccessControlPolicy?.AccessControlList?.Grant}");
}
catch (Exception ex)
{
    Console.WriteLine($"Operation failed: {ex.Message}");
}
// This sample code shows how to set the access control list (ACL) for a bucket.
// Before you run the sample code, configure the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables.

const OSS = require('ali-oss');

async function main() {
    const bucketName = 'example-bucket';

    const client = new OSS({
        region: 'oss-<region-id>',
        accessKeyId: process.env.OSS_ACCESS_KEY_ID,
        accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
        authorizationV4: true,
    });

    try {
        // Set the bucket ACL to private.
        // Valid values: 'private', 'public-read', and 'public-read-write'.
        await client.putBucketACL(bucketName, 'private');
        console.log('Bucket ACL set successfully.');

        // Get the bucket ACL.
        const result = await client.getBucketACL(bucketName);
        console.log(`Current bucket ACL: ${result.acl}`);
    } catch (err) {
        console.error('Operation failed:', err.message);
    }
}

main();

Track bucket ACL changes

Use ActionTrail to track bucket ACL changes, including who made each change and when. This helps investigate unusual access, data exposure, security alerts, or routine audits.

  1. Go to the ActionTrail Console. In the left-side navigation pane, choose .

  2. Select the region of the bucket. Set Service Name to Object Storage Service (OSS) and Event Name to PutBucketAcl. ActionTrail queries matching records automatically.

  3. Disable the Summary List option. In the Actions column of a change record, click View Details, then click Configure Timeline to view the before and after values.

FAQ

CDN origin: Is a public ACL required?

No. With a private ACL, you can still configure CDN to access the bucket. Set up access to a private origin bucket.

Related documents