Todos os produtos
Search
Central de documentação

Object Storage Service:Object ACLs

Última atualização: Sep 23, 2026

Object ACL oferece controle de acesso em nível de objeto no OSS. Use-o para conceder permissões de leitura ou gravação em objetos individuais, independentemente da ACL do bucket. Valores suportados: public-read-write, public-read, private e default (herda a ACL do bucket).

Notas de uso

  • O usuário RAM deve ter a permissão oss:PutObjectAcl. Para mais informações, consulte Grant a custom policy.

  • Se nenhuma ACL de objeto for configurada, o objeto herda a ACL do bucket.

  • Uma ACL de objeto definida explicitamente tem precedência sobre a ACL do bucket. Por exemplo, um objeto com ACL public-read permite acesso anônimo independentemente da ACL do bucket.

Tipos de ACLs

O OSS suporta as seguintes ACLs de objeto.

ACL

Descrição

public-read-write

Qualquer usuário, incluindo usuários anônimos, pode ler e gravar no objeto.

Aviso

Esta ACL permite que todos os usuários acessem e gravem dados no objeto pela Internet, o que pode causar acesso não autorizado, cobranças inesperadas ou upload de conteúdo proibido. Não defina a ACL do objeto como public-read-write, a menos que seja estritamente necessário.

public-read

Somente o proprietário do objeto pode gravar nele. Todos os demais usuários, incluindo usuários anônimos, têm apenas permissão de leitura.

Aviso

Esta ACL pode causar acesso não autorizado e cobranças inesperadas. Use-a com cautela.

private

Somente o proprietário do objeto pode lê-lo e gravá-lo. Outros usuários não têm acesso.

Nota

Você pode enviar URLs de objetos para compartilhar seus objetos privados com parceiros. Para mais informações, consulte (Recommended) V4 signatures in presigned URLs.

default

A ACL do objeto é a mesma do bucket em que ele está armazenado.

Métodos

Use the OSS console

  1. Faça login no OSS console.

  2. No painel de navegação à esquerda, clique em Buckets. Na página exibida, clique no nome do bucket de destino.

  3. No painel de navegação à esquerda, escolha Object Management > Objects.

  4. Especifique a ACL de um objeto.

    1. Acesse o painel Set ACL.

      Acesse o painel Set ACL por um dos seguintes métodos:

      • Localize o objeto na lista de objetos e clique em View Details na coluna Actions. Em seguida, clique em Set ACL ao lado de Object ACL.

      • Localize o objeto na lista de objetos e escolha more > Set ACL na coluna Actions.

    2. No painel Set ACL, configure a ACL conforme os requisitos do seu negócio.

  5. Clique em OK.

Use ossbrowser

O ossbrowser suporta as mesmas operações em nível de objeto que o OSS console. Siga as instruções na tela para modificar a ACL do objeto. Para mais informações, consulte 常用操作.

Use OSS SDKs

Os exemplos a seguir mostram como modificar a ACL de um objeto usando OSS SDKs para linguagens de programação comuns. Para outras linguagens, consulte 简介.

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 full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt. 
        String objectName = "testfolder/exampleobject.txt";
        // 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 OSSClient instance. 
        // Call the shutdown method to release associated resources when the OSSClient 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 {
            // Set the ACL of the object to public read. 
            ossClient.setObjectAcl(bucketName, objectName, CannedAccessControlList.PublicRead);
        } 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 = oss({ 
  // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Set bucket to the name of your bucket.
  bucket: 'yourbucketname'
});
  
async function setACL() {
  try {
    // Set yourObjectName to the full path of the object. The full path cannot contain the bucket name.
    await client.putACL('yourObjectName', 'private');
    console.log('Set ACL successfully');
  } catch (e) {
    console.error(e);
  }
}

setACL();
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
    <script>
      const client = new OSS({
        // Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
        region: "yourRegion",
        authorizationV4: true,
        // The temporary AccessKey pair (AccessKey ID and AccessKey secret) obtained from Security Token Service (STS).
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // The security token (SecurityToken) obtained from STS.
        stsToken: "yourSecurityToken",
        // Specify the bucket name. For example, examplebucket.
        bucket: "examplebucket",
      });

      async function getACL() {
        try {
          result = await client.getACL("examplefile.txt");
          console.log(result.acl);

          await client.putACL("examplefile.txt", "public-read");
          result = await client.getACL("examplefile.txt");
          console.log(result.acl);
        } catch (e) {
          console.log(e);
        }
      }

      getACL();
    </script>
  </body>
</html>
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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. 
var endpoint = "yourEndpoint";
// 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. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
var objectName = "exampleobject.txt";
// 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 string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
// Configure the ACL of the object. 
try
{
    // Call SetObjectAcl to configure the ACL of the object. 
    client.SetObjectAcl(bucketName, objectName, CannedAccessControlList.PublicRead);
    Console.WriteLine("Set Object:{0} ACL succeeded ", objectName);
}
catch (Exception ex)
{
    Console.WriteLine("Set Object ACL failed with error info: {0}", ex.Message);
}
// Query the ACL of the object. 
try
{
    // Call GetObjectAcl to query the ACL of the object. 
    var result = client.GetObjectAcl(bucketName, objectName);
    Console.WriteLine("Get Object ACL succeeded, Id: {0}  ACL: {1}",
        result.Owner.Id, result.ACL.ToString());
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
// Specify the bucket name and the full path of the object. Example: examplebucket and exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
GetObjectACLRequest request = new GetObjectACLRequest("examplebucket", "exampledir/exampleobject.txt");
// OSS SDK for Android does not support setting object ACLs. You can only get object ACLs.
// The following code shows how to get the ACL of an object.
oss.asyncGetObjectACL(request, new OSSCompletedCallback<GetObjectACLRequest, GetObjectACLResult>() {
    @Override
    public void onSuccess(GetObjectACLRequest request, GetObjectACLResult result) {
        Log.d("GetObjectACL", "Success!");
        Log.d("ObjectAcl", result.getObjectACL());
        Log.d("Owner", result.getObjectOwner());
        Log.d("ID", result.getObjectOwnerID());
    }

    @Override
    public void onFailure(GetObjectACLRequest request, ClientException clientException, ServiceException serviceException) {
        // Request exceptions.
        if (clientException != null) {
            // Client exceptions, such as network exceptions.
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            // Server exceptions.
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
OSSPutObjectACLRequest *request = [OSSPutObjectACLRequest new];
// Specify the name of the bucket. Example: examplebucket. 
request.bucketName = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt. 
request.objectKey = @"exampleobject.txt";
/**
 * Configure the object ACL. 
 * public-read
 * private
 * public-read-write
 * default
 */
request.acl = @"private";

OSSTask * putObjectACLTask = [client putObjectACL:request];
[putObjectACLTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"put object ACL success!");
    } else {
        NSLog(@"put object ACL failed, error: %@", task.error);
    }
    return nil;
}];
// Implement synchronous blocking to wait for the task to complete. 
// [putObjectACLTask waitUntilFinished];
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the bucket name. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. The full path cannot include the bucket name. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";

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

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

    /* Set the object access permissions. */
    SetObjectAclRequest request(BucketName, ObjectName);
    request.setAcl(CannedAccessControlList::Private);
    auto outcome = client.SetObjectAcl(request);

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

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is 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);
    /* Initialize an aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run this 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"));
    // The following two parameters also need to be configured.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether a CNAME is used. 0 indicates that no CNAME is used. */
    options->config->is_cname = 0;
    /* Set 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 at the program entrance to initialize global resources such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* The memory pool (pool) is used for memory management and is equivalent to apr_pool_t. The implementation code is in the apr library. */
    aos_pool_t *pool;
    /* Create a new memory pool. The second parameter is NULL, which indicates that the new memory pool does not inherit from another memory pool. */
    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 memory to options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client options oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    oss_acl_e oss_acl = OSS_ACL_PRIVATE;
    /* Set the object ACL. */
    resp_status = oss_put_object_acl(oss_client_options, &bucket, &object, oss_acl, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("put object acl success!\n"); 
    } else {
        printf("put object acl failed!\n"); 
    }
    /* Get the object ACL. */
    aos_string_t oss_acl_string;
    resp_status = oss_get_object_acl(oss_client_options, &bucket, &object, &oss_acl_string, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("get object acl success!\n");
        printf("acl: %s \n", oss_acl_string.data);
    } else {
        printf("get object acl failed!\n");
    }
    /* Release the memory pool. This releases the memory allocated to resources during 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(
  # The China (Hangzhou) region is used as an example. Replace the endpoint with the one for your region.
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the bucket name. For example, examplebucket.
bucket = client.get_bucket('examplebucket')
# Specify the full path of the object. The full path cannot contain the bucket name. For example, exampledir/example.txt.
# Get the ACL of the object that is set during the upload.
acl = bucket.get_object_acl('exampledir/example.txt')
puts acl
# Modify the ACL of the object.
bucket.set_object_acl('exampledir/example.txt', Aliyun::OSS::ACL::PUBLIC_READ)
acl = bucket.get_object_acl('exampledir/example.txt')
puts 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 where the bucket is located.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// The init function is 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.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

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

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

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

	// Check whether the object name is empty.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and set 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 set the ACL of the object.
	putRequest := &oss.PutObjectAclRequest{
		Bucket: oss.Ptr(bucketName),  // The name of the bucket.
		Key:    oss.Ptr(objectName),  // The name of the object.
		Acl:    oss.ObjectACLPrivate, // Set the ACL of the object to private.
	}

	// Execute the operation to set the ACL of the object.
	putResult, err := client.PutObjectAcl(context.TODO(), putRequest)
	if err != nil {
		log.Fatalf("failed to put object acl %v", err)
	}

	// Print the result of setting the object ACL.
	log.Printf("put object acl result:%#v\n", putResult)

	// Create a request to obtain the ACL (access control list) of the object.
	getRequest := &oss.GetObjectAclRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
	}

	// Execute the operation to obtain the ACL of the object.
	getResult, err := client.GetObjectAcl(context.TODO(), getRequest)
	if err != nil {
		log.Fatalf("failed to get object acl %v", err)
	}

	// Print the result of obtaining the object ACL.
	log.Printf("get object acl result:%#v\n", getResult)
}
<?php

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

use AlibabaCloud\Oss\V2 as Oss;

$optsdesc = [
    "region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
    "endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
    "bucket" => ['help' => 'The name of the bucket', 'required' => True],
    "key" => ['help' => 'The name of the object', 'required' => True],
];

// Create an array of long options required by getopt. Example: --region:.
$longopts = array_map(function ($key) {
    return "$key:";
}, array_keys($optsdesc));

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

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

// Extract the values of the parameters.
$region = $options["region"];
$bucket = $options["bucket"];
$key = $options["key"];

// Obtain access credentials (AccessKey ID and AccessKey secret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();

// Load the default configurations and specify the credential provider and region.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);

// If the endpoint parameter is specified, it will be configured as the custom access URL.
if (isset($options["endpoint"])) {
    $cfg->setEndpoint($options["endpoint"]);
}

// Initialize the OSSClient instance.
$client = new Oss\Client($cfg);

// Create a PutObjectAclRequest object and specify the bucket name, object key and ACL.
$request = new Oss\Models\PutObjectAclRequest($bucket, $key, Oss\Models\ObjectACLType::PUBLIC_READ);

// Set the ACL of the object to public-read.
$result = $client->putObjectAcl($request);

// Output the HTTP status code and request ID from the response.
printf(
    'status code:' . $result->statusCode . PHP_EOL .
    'request id:' . $result->requestId
);
import argparse
import alibabacloud_oss_v2 as oss

# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put object acl sample")
# Add required parameters: region, bucket name, object key, and access control list (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)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--acl', help='Specify the access permission ACL for the object.', required=True)

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

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

    # Use the default configurations of the SDK.
    cfg = oss.config.load_default()
    # Set the credential provider.
    cfg.credentials_provider = credentials_provider
    # Set the region provided by the user.
    cfg.region = args.region
    # If an endpoint is provided, set the endpoint in the configuration.
    if args.endpoint is not None:
        cfg.endpoint = args.endpoint

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

    # Set the ACL of the object.
    result = client.put_object_acl(oss.PutObjectAclRequest(
        bucket=args.bucket,  # The bucket name.
        key=args.key,  # The object key.
        acl=args.acl,  # The new ACL value.
    ))

    # Print the output information after setting the ACL.
    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' version id: {result.version_id},'
    )

    # Obtain and print the current ACL settings of the object.
    result = client.get_object_acl(oss.GetObjectAclRequest(
        bucket=args.bucket,
        key=args.key,
    ))

    print(f'status code: {result.status_code},'
          f' request id: {result.request_id},'
          f' acl: {result.acl},'
          f' version id: {result.version_id},'
    )

# Call the main function when this script is run directly.
if __name__ == "__main__":
    main()

Use ossutil

Use o ossutil para configurar ou modificar ACLs de objetos. Para instruções de instalação, consulte Install ossutil.

O exemplo a seguir define a ACL do objeto como private.

ossutil api put-object-acl --bucket examplebucket --key exampleobject --object-acl private

Para mais informações, consulte put-object-acl.

Operação de API relacionada

Os métodos acima são baseados na API RESTful, que pode ser chamada diretamente para integrações personalizadas. Chamadas diretas à API exigem o cálculo de assinatura. Para mais informações, consulte PutObjectACL.

Referências