All Products
Search
Document Center

Object Storage Service:Manage object permissions by using bucket ACLs

Last Updated:Aug 01, 2025

If your permission requirements change, you can modify the bucket ACL. The permissions for all objects that inherit the ACL are automatically updated to ensure consistency. If you do not specify an access control list (ACL) when you upload an object, the bucket ACL is automatically applied.

Access control list types

A bucket has the following three types of access control lists (ACLs):

Permission value

Permission description

public-read-write

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

Warning

Any user on the Internet can access the objects in the bucket and write data to the bucket. This may cause data breaches and a sharp increase in fees. If malicious users write illegal information to the bucket, your legitimate rights and interests may be infringed. We recommend that you do not configure the public-read-write permission except for special scenarios.

public-read

Public read: Only the bucket owner can write objects to the bucket. Anyone, including anonymous users, can read objects in the bucket.

Warning

Any user on the Internet can access the objects in the bucket. This may cause data breaches and a sharp increase in fees. Proceed with caution.

private (default)

Private: Only the bucket owner can read and write objects in the bucket. Other users cannot access the objects in the bucket.

Set or modify a bucket ACL

You can set a bucket ACL when you create a bucket or modify the ACL after the bucket is created.

OSS console

  1. Log on to the OSS console.

  2. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  3. In the navigation pane on the left, choose Permission Control > Access Control List.

  4. On the Access Control List tab, click Settings to modify the bucket ACL as needed.

  5. Click Save.

Command line interface (ossutil)

You can use the command line interface (CLI) tool ossutil to configure a bucket ACL. For more information about how to install ossutil, see Install ossutil.

The following command sets the access permission for the bucket named examplebucket to private.

ossutil api put-bucket-acl --bucket examplebucket --acl private

For more information about this command, see put-bucket-acl.

ossbrowser

The bucket-level operations supported by ossbrowser are similar to those supported by the console. Follow the instructions in the ossbrowser interface to modify the bucket ACL. For more information about how to use ossbrowser, see Common operations.

OSS SDK

The following code provides examples of how to modify the ACL of a bucket using common SDKs. For code examples for other SDKs, see SDK Introduction.

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.CannedAccessControlList;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSS Client instance. 
        // Call the shutdown method to release associated resources when the OSS Client is no longer in use.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Specify the ACL of the bucket. In this example, the ACL of the examplebucket bucket is set to private. 
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.Private);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
const OSS = require('ali-oss');

const client = new OSS({
  // The region is set to Hangzhou (oss-cn-hangzhou) in this example. Specify the actual region.
  region: '<Your region>',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the bucket name.
  bucket: 'yourBucketName',
});


async function putBucketACL() {
// Set the ACL of the bucket to private.
  const acl = 'private'
  try {
    await client.putBucketACL('<Your Bucket Name>', acl)
  } catch (error) {
    console.log(error)
  }
}

putBucketACL()
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize resources such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Set the ACL of the bucket to private. */
    SetBucketAclRequest request(BucketName, CannedAccessControlList::Private);
    auto outcome = client.SetBucketAcl(request);

    if (outcome.isSuccess()) {    
        std::cout << " setBucketAcl successfully " << std::endl;
    }
    else {
        /* Handle exceptions. */
        std::cout << "SetBucketAcl fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources such as network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";

/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{

    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */    
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Specify two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use CNAME to access OSS. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Configure network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the parameters. */
    aos_string_t bucket;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    /* Assign char* data to a bucket of the aos_string_t type. */
    aos_str_set(&bucket, bucket_name);
    /* Set the ACL of the bucket to public-read (OSS_ACL_PUBLIC_READ). */
    resp_status = oss_put_bucket_acl(oss_client_options, &bucket, OSS_ACL_PUBLIC_READ, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("set bucket acl succeeded\n");
    } else {
        printf("set bucket acl failed\n");
    }
    /* Release the memory pool. This operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'

client = Aliyun::OSS::Client.new(
  # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket. 
bucket = client.get_bucket('examplebucket')
bucket.acl = Aliyun::OSS::ACL::PUBLIC_READ
puts bucket.acl
package main

import (
	"context"
	"flag"
	"log"

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

// Define global variables.
var (
	region     string // The region in which your bucket is located.
	bucketName string // The name of the bucket.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to configure the ACL of the bucket.
	putRequest := &oss.PutBucketAclRequest{
		Bucket: oss.Ptr(bucketName),  // The name of the bucket.
		Acl:    oss.BucketACLPrivate, // Set the ACL to private.
	}

	// Perform the operation to configure the ACL.
	putResult, err := client.PutBucketAcl(context.TODO(), putRequest)
	if err != nil {
		log.Fatalf("failed to put bucket acl %v", err)
	}

	// Display the result.
	log.Printf("put bucket acl result: %#v\n", putResult)

	// Create a request to query the ACL.
	getRequest := &oss.GetBucketAclRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket
	}

	// Perform the operation to query the ACL.
	getResult, err := client.GetBucketAcl(context.TODO(), getRequest)
	if err != nil {
		log.Fatalf("failed to get bucket acl %v", err)
	}

	// Display the result.
	log.Printf("get bucket acl result:%#v\n", getResult)
}
import argparse
import alibabacloud_oss_v2 as oss

# Create a command line argument parser and add description information
parser = argparse.ArgumentParser(description="put bucket acl sample")
# Add required command line arguments: region, bucket, and acl
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
# Add optional command line argument: endpoint, used to specify the domain name for other services to access OSS
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
# Add required command line argument: acl, used to specify the access permission ACL for the bucket, such as private, public-read, public-read-write
parser.add_argument('--acl', help='Specify the access permission ACL for the bucket.', required=True)

def main():
    # Parse command line arguments
    args = parser.parse_args()

    # Load authentication information from environment variables
    credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()

    # Use SDK default configuration
    cfg = oss.config.load_default()
    # Set credentials provider
    cfg.credentials_provider = credentials_provider
    # Set region
    cfg.region = args.region
    # If endpoint is provided, update endpoint in the configuration
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

    # Create OSS client
    client = oss.Client(cfg)

    # Call put_bucket_acl method to set the bucket ACL
    result = client.put_bucket_acl(oss.PutBucketAclRequest(
        bucket=args.bucket,
        acl=args.acl,
    ))

    # Print the status code and request ID of the request
    print(f'status code: {result.status_code}, request id: {result.request_id}')

    # Obtain the ACL of the specified bucket
    result = client.get_bucket_acl(oss.GetBucketAclRequest(
        bucket=args.bucket,
    ))

    # Print the status code, request ID, and ACL information in the result
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' acl: {result.acl},'
    )

if __name__ == "__main__":
    main()
<?php

// Introduce autoload files to load dependent libraries.
require_once __DIR__ . '/../vendor/autoload.php';

use AlibabaCloud\Oss\V2 as Oss;

// Specify descriptions for command line parameters.
$optsdesc = [
    "region" => ['help' => The region in which the bucket is located.', 'required' => True], // (Required) Specify the region in which the bucket is located.
    "endpoint" => ['help' => The domain names that other services can use to access OSS', 'required' => False], // (Optional) Specify the endpoint that can be used by other services to access OSS.
    "bucket" => ['help' => The name of the bucket, 'required' => True], // (Required) Specify the name of the bucket.
];

// Generate a long options list to parse the command line parameters.
$longopts = \array_map(function ($key) {
    return "$key:"; // Add a colon (:) to the end of each parameter to indicate that a value is required.
}, array_keys($optsdesc));

// Parse the command line parameters.
$options = getopt("", $longopts); 

// Check whether the required parameters are configured.
foreach ($optsdesc as $key => $value) {
    if ($value['required'] === True && empty($options[$key])) {
        $help = $value['help'];
        echo "Error: the following arguments are required: --$key, $help"; // Specify that the required parameters are not configured.
        exit(1); 
    }
}

// Obtain the values of the command line parameters.
$region = $options["region"]; // The region in which the bucket is located.
$bucket = $options["bucket"]; // The name of the bucket.

// Use environment variables to load the AccessKey ID and AccessKey secret.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Use the default configurations of the SDK.
$cfg = Oss\Config::loadDefault();

// Specify the credential provider.
$cfg->setCredentialsProvider($credentialsProvider);

// Specify the region.
$cfg->setRegion($region);

// Specify the endpoint if an endpoint is provided.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Create an OSSClient instance.
$client = new Oss\Client($cfg);

// Create a PutBucketAclRequest object and set the bucket ACL to private.
$request = new Oss\Models\PutBucketAclRequest(
      bucket: $bucket, 
      acl: Oss\Models\BucketACLType::PRIVATE);

// Use the putBucketAcl method to specify the bucket ACL.
$result = $client->putBucketAcl($request);

// Display the result.
printf(
    'status code:' . $result->statusCode . PHP_EOL . // The returned HTTP status code.
    'request id:' . $result->requestId // The request ID of the request, which is the unique identifier of the request.
);

API

If your program has highly customized requirements, you can send REST API requests directly. In this case, you must manually write the code to calculate signatures. For more information, see PutBucketAcl.

Query the modification records of a bucket ACL

You can use ActionTrail to track who modified a bucket ACL and when. This is useful if you detect abnormal bucket access, receive a security alert, or need to perform a regular audit.

  1. On the Event Query page, you can view the modification records of the bucket ACL by selecting the region where the bucket is located, setting Service Name to Object Storage Service (Oss), and setting Event Name to PutBucketAcl.

  2. To the right of the Bucket ACL change record, click View Details, and then click Configuration Timeline to view the values before and after the change.

FAQ

Does the ACL of an OSS bucket need to be public-read or public-read-write when Alibaba Cloud CDN retrieves data from OSS?

No, it does not. If the bucket ACL is private, you can enable CDN to retrieve data from the private OSS bucket. For more information, see Enable back-to-origin to a private OSS bucket.

References

  • To grant fine-grained permissions to other users on a long-term basis, such as read-only or write-only permissions for files with a specified prefix in a bucket, use a bucket policy or a RAM policy. For more information, see Common examples of bucket policies and Common examples of RAM policies.

  • To temporarily grant fine-grained permissions to other users, such as the permission to list all files in a bucket, use Security Token Service (STS) for temporary authorization. For more information, see Use STS credentials to access OSS.