A bucket policy é uma política de autorização do Object Storage Service (OSS) para buckets. Esse recurso permite conceder ou negar acesso granular a recursos específicos do OSS para usuários autenticados — como contas Alibaba Cloud, usuários do Resource Access Management (RAM) e funções RAM — ou visitantes anônimos. Por exemplo, você pode conceder permissões de somente leitura em recursos específicos do OSS a um usuário RAM de outra conta Alibaba Cloud.
Observações
Compreenda o funcionamento das bucket policies antes de configurá-las. Para mais informações, consulte Bucket Policy.
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, utilize um endpoint interno. Para obter detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
O exemplo abaixo demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação via credenciais do Security Token Service (STS), consulte Criar uma instância OssClient.
Defina uma bucket policy exige a permissão
oss:PutBucketPolicy. Obter uma bucket policy exige a permissãooss:GetBucketPolicy. Exclua uma bucket policy exige a permissãooss:DeleteBucketPolicy. Para mais informações, consulte Conceder uma política personalizada.
Configure uma bucket policy
O código de exemplo a seguir define uma bucket policy:
#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 bucket policy
O código de exemplo a seguir obtém uma bucket policy:
#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;
}
Exclua uma bucket policy
O código de exemplo a seguir exclui uma bucket policy:
#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 detalhes sobre a operação de API que define uma bucket policy, consulte PutBucketPolicy.
Para obter detalhes sobre a operação de API que recupera uma bucket policy, consulte GetBucketPolicy.
Para obter detalhes sobre a operação de API que exclui uma bucket policy, consulte DeleteBucketPolicy.