Gerenciar o acesso a buckets do Amazon S3 usando políticas de bucket - AWS SDK para C++

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Gerenciar o acesso a buckets do Amazon S3 usando políticas de bucket

Você pode definir, acessar ou excluir uma política de bucket para gerenciar o acesso aos buckets do Amazon S3.

Pré-requisitos

Antes de começar, recomendamos que você leia Getting started using the AWS SDK para C++.

Baixe o exemplo código de código e crie a solução conforme descrito em Conceitos básicos dos exemplos de código.

Para executar os exemplos, o perfil de usuário que seu código usa para fazer as solicitações deve ter as permissões adequadas na AWS (para o serviço e a ação). Para acessar mais informações, consulte Fornecer credenciais da AWS.

Definir uma política de bucket

É possível definir a política para um bucket específico do S3 chamando a função PutBucketPolicy do S3Client e fornecendo o nome do bucket e a representação JSON da política em uma PutBucketPolicyRequest.

Código da

//! Build a policy JSON string. /*! \param userArn: Aws user Amazon Resource Name (ARN). For more information, see https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-arns. \param bucketName: Name of a bucket. \return String: Policy as JSON string. */ Aws::String getPolicyString(const Aws::String &userArn, const Aws::String &bucketName) { return "{\n" " \"Version\":\"2012-10-17\",\n" " \"Statement\":[\n" " {\n" " \"Sid\": \"1\",\n" " \"Effect\": \"Allow\",\n" " \"Principal\": {\n" " \"AWS\": \"" + userArn + "\"\n"" },\n" " \"Action\": [ \"s3:getObject\" ],\n" " \"Resource\": [ \"arn:aws:s3:::" + bucketName + "/*\" ]\n" " }\n" " ]\n" "}"; }
bool AwsDoc::S3::putBucketPolicy(const Aws::String &bucketName, const Aws::String &policyBody, const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client s3Client(clientConfig); std::shared_ptr<Aws::StringStream> request_body = Aws::MakeShared<Aws::StringStream>(""); *request_body << policyBody; Aws::S3::Model::PutBucketPolicyRequest request; request.SetBucket(bucketName); request.SetBody(request_body); Aws::S3::Model::PutBucketPolicyOutcome outcome = s3Client.PutBucketPolicy(request); if (!outcome.IsSuccess()) { std::cerr << "Error: putBucketPolicy: " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Set the following policy body for the bucket '" << bucketName << "':" << std::endl << std::endl; std::cout << policyBody << std::endl; } return outcome.IsSuccess(); }
nota

A classe do utilitário Aws::Utils::Json::JsonValue pode ser usada para ajudar você a criar objetos JSON válidos para transmitir à PutBucketPolicy.

Veja o exemplo completo no GitHub.

Obter uma política de bucket

Para recuperar a política de um bucket do Amazon S3, chame a função GetBucketPolicy do S3Client, transmitindo a ela o nome do bucket em uma GetBucketPolicyRequest.

Código da

bool AwsDoc::S3::getBucketPolicy(const Aws::String &bucketName, const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client s3Client(clientConfig); Aws::S3::Model::GetBucketPolicyRequest request; request.SetBucket(bucketName); Aws::S3::Model::GetBucketPolicyOutcome outcome = s3Client.GetBucketPolicy(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &err = outcome.GetError(); std::cerr << "Error: getBucketPolicy: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { Aws::StringStream policy_stream; Aws::String line; outcome.GetResult().GetPolicy() >> line; policy_stream << line; std::cout << "Retrieve the policy for bucket '" << bucketName << "':\n\n" << policy_stream.str() << std::endl; } return outcome.IsSuccess(); }

Veja o exemplo completo no GitHub.

Excluir uma política de bucket

Para excluir uma política de bucket, chame a função DeleteBucketPolicy do S3Client, fornecendo o nome do bucket em uma DeleteBucketPolicyRequest.

Código da

bool AwsDoc::S3::deleteBucketPolicy(const Aws::String &bucketName, const Aws::S3::S3ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::DeleteBucketPolicyRequest request; request.SetBucket(bucketName); Aws::S3::Model::DeleteBucketPolicyOutcome outcome = client.DeleteBucketPolicy(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &err = outcome.GetError(); std::cerr << "Error: deleteBucketPolicy: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "Policy was deleted from the bucket." << std::endl; } return outcome.IsSuccess(); }

Essa função será bem-sucedida, mesmo se o bucket ainda não tiver uma política. Se você especificar um nome de bucket não existente ou se não tiver acesso ao bucket, um AmazonServiceException será lançado.

Veja o exemplo completo no GitHub.

Mais informações