Todos os produtos
Search
Central de documentação

Object Storage Service:Gerenciar ACLs de objetos (OSS SDK for Java 1.0)

Última atualização: Oct 09, 2026

Além das listas de controle de acesso (ACLs) no nível do bucket, o Object Storage Service (OSS) oferece ACLs no nível do objeto. Você pode configurar a ACL de um objeto ao fazer o upload ou alterar a ACL de um objeto já enviado.

Observações de uso

  • Os exemplos deste tópico usam o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre as regiões e os endpoints compatíveis, consulte Regions and endpoints.

  • Neste tópico, as credenciais de acesso são obtidas de variáveis de ambiente. Para obter mais informações, consulte 配置访问凭证.

  • Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar-se com credenciais do Security Token Service (STS), consulte Client configuration.

  • Para configurar a ACL de um objeto, você deve ter a permissão oss:PutObjectAcl. Para consultar as ACLs de objetos, você deve ter a permissão oss:GetObjectAcl. Para saber mais, consulte Grant a custom policy.

Tipos de ACL

A tabela a seguir descreve as ACLs que você pode configurar para um objeto.

Nota

A ACL de um objeto tem precedência sobre a ACL do bucket em que ele está armazenado. Por exemplo, se a ACL de um objeto em um bucket privado estiver definida como leitura pública, todos os usuários, inclusive os anônimos, podem ler o objeto.

Tipo de ACL

Descrição

Valor

Herdada do bucket

A ACL do objeto é igual à do bucket em que está armazenado. Esta é a ACL padrão de um objeto.

CannedAccessControlList.Default

Privada

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

CannedAccessControlList.Private

Leitura pública

Somente o proprietário do objeto pode gravá-lo. Outros usuários, inclusive os anônimos, podem apenas lê-lo.

Aviso

Isso pode causar acesso não autorizado e custos inesperados. Recomenda-se cautela ao usar esta ACL.

CannedAccessControlList.PublicRead

Leitura e gravação públicas

Todos os usuários, inclusive os anônimos, podem lê-lo e gravá-lo.

Aviso

Esta ACL permite que todos os usuários acessem e gravem dados no objeto pela Internet. Isso pode causar acesso não autorizado, custos inesperados ou upload de conteúdo proibido. Não defina a ACL do objeto como leitura e gravação públicas, a menos que necessário.

CannedAccessControlList.PublicReadWrite

Configurar a ACL de um objeto

O código de exemplo a seguir demonstra como configurar a ACL de um objeto:

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();
            }
        }
    }
}            

Consultar a ACL de um objeto

O código de exemplo a seguir demonstra como consultar a ACL de um objeto:

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

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 {
            // Query the ACL of the object. 
            ObjectAcl objectAcl = ossClient.getObjectAcl(bucketName, objectName);
            System.out.println(objectAcl.getPermission().toString());
        } 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();
            }
        }
    }
}            

Referências

  • Para obter o código de exemplo completo para o gerenciamento de ACLs de objetos, visite o GitHub.

  • Para obter mais informações sobre a operação de API para configurar a ACL de um objeto, consulte PutObjectACL.

  • Para saber mais sobre a operação de API para consultar a ACL de um objeto, consulte GetObjectACL.