Defina e obtenha ACLs de bucket para controlar as permissões de leitura e gravação nos objetos de um bucket.
Observações
Este tópico usa 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 do OSS, use um endpoint interno. Para obter mais informações sobre as regiões e endpoints do OSS, consulte Regions and endpoints.
Este tópico demonstra como criar uma instância do OSSClient com um endpoint do OSS. Em configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Create an OssClient instance.
Para definir a ACL de um bucket, é necessário ter a permissão
oss:PutBucketAcl. Para obter a ACL de um bucket, é necessário ter a permissãooss:GetBucketAcl. Para saber mais, consulte Grant a custom policy.
Defina a ACL de um bucket
O OSS oferece suporte às seguintes ACLs de bucket.
|
ACL |
Descrição |
Método |
|
Privado |
Somente o proprietário do bucket pode ler e gravar objetos no bucket. Outros usuários não podem acessar os objetos. |
CannedAccessControlList::Private |
|
Leitura pública |
Somente o proprietário do bucket pode gravar objetos no bucket. Outros usuários, incluindo usuários anônimos, podem apenas ler os objetos. Aviso
Definir a ACL de um bucket como leitura pública permite que qualquer pessoa na internet leia os objetos armazenados nele. Isso pode levar à exposição não intencional de dados e a cobranças inesperadas. Tenha cuidado. |
CannedAccessControlList::PublicRead |
|
Leitura e gravação públicas |
Todos os usuários, incluindo usuários anônimos, podem ler e gravar objetos no bucket. Aviso
Definir a ACL de um bucket como leitura e gravação públicas permite que qualquer pessoa na internet leia e grave objetos armazenados nele. Isso representa um risco significativo à segurança, o que pode causar exposição de dados, cobranças inesperadas e o upload de conteúdo malicioso ou ilegal para o seu bucket. Evite usar esta ACL, a menos que seja estritamente necessário. |
CannedAccessControlList::PublicReadWrite |
O código de exemplo a seguir define a ACL de um bucket:
#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 the SDK. This must be called before using the SDK. */
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 the error. */
std::cout << "SetBucketAcl fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Shut down the SDK to release resources. */
ShutdownSdk();
return 0;
}
Obtenha a ACL de um bucket
O código a seguir obtém a ACL do bucket:
#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 the SDK. This must be called before using the SDK. */
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);
/* Get the ACL of the bucket. */
GetBucketAclRequest request(BucketName);
auto outcome = client.GetBucketAcl(request);
if (outcome.isSuccess()) {
std::cout << "getBucketAcl success, acl: " << outcome.result().Acl() << std::endl;
}
else {
/* Handle the error. */
std::cout << "getBucketAcl fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Shut down the SDK to release resources. */
ShutdownSdk();
return 0;
}
Referências
Para acessar o código de exemplo completo sobre como gerenciar ACLs de bucket, visite o GitHub.
Para obter mais informações sobre a operação de API para definir a ACL de um bucket, consulte PutBucketAcl.
Para saber mais sobre a operação de API para obter a ACL de um bucket, consulte GetBucketAcl.