A política de bucket é uma política de autorização que o Object Storage Service (OSS) fornece para buckets. Use uma política de bucket para conceder ou negar acesso de granularidade fina a recursos específicos do OSS a usuários autenticados, como contas da Alibaba Cloud, usuários do Resource Access Management (RAM) e funções do RAM, ou a visitantes anônimos. Por exemplo, você pode conceder permissões de somente leitura em recursos específicos do OSS a um usuário do RAM pertencente a outra conta da Alibaba Cloud.
Observações
Certifique-se de entender as políticas de bucket antes de configurar uma. Para obter mais informações, consulte Bucket Policy.
Neste tópico, usa-se 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.
O exemplo a seguir demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para 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 uma política de bucket, é necessária a permissão
oss:PutBucketPolicy. Para obter uma política, você precisa da permissãooss:GetBucketPolicy. Já para excluí-la, é obrigatória a permissãooss:DeleteBucketPolicy. Para obter mais informações, consulte Grant a custom policy.
Definir uma política de bucket
Veja a seguir o código de exemplo para definir uma política de bucket:
#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. For example, examplebucket. */
std::string BucketName = "examplebucket";
/* 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);
/* The following example shows how a resource owner (the owner of the bucket with UID 174649585760xxxx) uses a bucket policy to grant a specified user (a RAM user with UID 20214760404935xxxx) the permissions to list all files in the examplebucket. */
std::string policy =
R"(
{
"Statement": [
{
"Action": [
"oss:GetObject",
"oss:ListObjects"
],
"Principal": [
"20214760404935xxxx"
],
"Effect" : "Allow",
"Resource" : ["acs:oss:*:174649585760xxxx:examplebucket/*"]
}
],
"Version": "1"
}
)";
SetBucketPolicyRequest request(BucketName);
request.setPolicy(policy);
auto outcome = client.SetBucketPolicy(request);
if (!outcome.isSuccess()) {
/* Handle the exception. */
std::cout << "Set Bucket Policy fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
Obter uma política de bucket
Veja a seguir o código de exemplo para obter uma política de bucket:
#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. For example, examplebucket. */
std::string BucketName = "examplebucket";
/* 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);
/* Get the bucket policy configuration. */
GetBucketPolicyRequest request(BucketName);
auto outcome = client.GetBucketPolicy(request);
if (!outcome.isSuccess()) {
/* Handle the exception. */
std::cout << "Get Bucket Policy fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
return -1;
}
/* Print the configuration information. */
std::cout << outcome.result().Policy() << std::endl;
/* Release network resources. */
ShutdownSdk();
return 0;
}
Excluir uma política de bucket
Veja a seguir o código de exemplo para excluir uma política de bucket:
#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. For example, examplebucket. */
std::string BucketName = "examplebucket";
/* 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);
/* Delete the bucket policy. */
DeleteBucketPolicyRequest request(BucketName);
auto outcome = client.DeleteBucketPolicy(request);
if (!outcome.isSuccess()) {
/* Handle the exception. */
std::cout << "Delete Bucket Policy fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
}
/* Release network resources. */
ShutdownSdk();
return 0;
}
Referências
Para obter mais informações sobre a operação de API para definir uma política de bucket, consulte PutBucketPolicy.
Para saber mais sobre a operação de API para obter uma política de bucket, consulte GetBucketPolicy.
Consulte DeleteBucketPolicy para obter mais informações sobre a operação de API para excluir uma política de bucket.