

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# バケットポリシーを使用した Amazon S3 バケットへのアクセスの管理
<a name="examples-s3-bucket-policies"></a>

*バケットポリシー*を設定、取得、または削除して、Amazon S3 バケットへのアクセスを管理できます。

## 前提条件
<a name="codeExamplePrereq"></a>

作業を始める前に「[AWS SDK for C\+\+の開始方法](getting-started.md)」を読むことをお勧めします。

コード例をダウンロードし、「[コード例の開始方法](getting-started-code-examples.md)」の説明に従ってソリューションをビルドします。

例を実行するには、コードがリクエストを行うために使用するユーザープロファイルに適切なアクセス許可が必要です AWS ( サービスと アクション用）。詳細については、[AWS 「認証情報の提供](credentials.md)」を参照してください。

## バケットポリシーの設定
<a name="set-s3-bucket-policy"></a>

特定の S3 バケットに対するバケットポリシーを設定するには、`S3Client` の `PutBucketPolicy` 関数の呼び出しで、バケット名とポリシーの JSON 表現を [PutBucketPolicyRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_put_bucket_policy_request.html) で指定して渡します。

 **コード** 

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

**注記**  
[Aws::Utils::Json::JsonValue](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-core/html/class_aws_1_1_utils_1_1_json_1_1_json_value.html) ユーティリティクラスを使用すると、有効な JSON オブジェクトをコンストラクトして `PutBucketPolicy` に渡すことができます。

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/put_bucket_policy.cpp) で完全な例をご覧ください。

## バケットポリシーの取得
<a name="get-s3-bucket-policy"></a>

Amazon S3 バケットのポリシーを取得するには、`S3Client` の `GetBucketPolicy` 関数の呼び出しで、バケット名を [GetBucketPolicyRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_get_bucket_policy_request.html) で指定して渡します。

 **Code** 

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

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/get_bucket_policy.cpp) で完全な例をご覧ください。

## バケットポリシーの削除
<a name="delete-s3-bucket-policy"></a>

バケットポリシーを削除するには、`S3Client` の `DeleteBucketPolicy` 関数の呼び出しで、バケット名を [DeleteBucketPolicyRequest](https://docs.aws.amazon.com/sdk-for-cpp/latest/api/aws-cpp-sdk-s3/html/class_aws_1_1_s3_1_1_model_1_1_delete_bucket_policy_request.html) で指定して渡します。

 **コード** 

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

バケットにポリシーが存在しない場合でも、この関数は成功します。指定した名前のバケットが存在していないか、バケットへのアクセス権がない場合は、`AmazonServiceException` がスローされます。

[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/s3/delete_bucket_policy.cpp) で完全な例をご覧ください。

## 詳細情報
<a name="more-info"></a>
+  「Amazon Simple Storage Service API リファレンス」の「[PutBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/PutBucketPolicy.html)」
+  「Amazon Simple Storage Service API リファレンス」の「[GetBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/GetBucketPolicy.html)」
+  「Amazon Simple Storage Service API リファレンス」の「[DeleteBucketPolicy](https://docs.aws.amazon.com/AmazonS3/latest/API/DeleteBucketPolicy.html)」
+  「Amazon Simple Storage Service ユーザーガイド」の「[アクセスポリシー言語の概要](https://docs.aws.amazon.com/AmazonS3/latest/dev/access-policy-language-overview.html)」
+  「Amazon Simple Storage Service ユーザーガイド」の「[バケットポリシーの例](https://docs.aws.amazon.com/AmazonS3/latest/dev/example-bucket-policies.html)」