

适用于 JavaScript 的 AWS SDK v2 已终止支持。建议您迁移到 [适用于 JavaScript 的 AWS SDK v3](https://docs.aws.amazon.com//sdk-for-javascript/v3/developer-guide/)。有关更多详情和如何迁移的信息，请参阅本[公告](https://aws.amazon.com/blogs//developer/announcing-end-of-support-for-aws-sdk-for-javascript-v2/)。

# 使用 Amazon S3 存储桶策略
<a name="s3-example-bucket-policies"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/zh_cn/sdk-for-javascript/v2/developer-guide/images/nodeicon.png)

**此 Node.js 代码示例演示：**
+ 如何检索 Amazon S3 桶的桶策略。
+ 如何添加或更新 Amazon S3 桶的桶策略。
+ 如何删除 Amazon S3 桶的桶策略。

## 情景
<a name="w2aac20c25c27c15b9"></a>

本示例使用一系列 Node.js 模块来检索、设置或删除 Amazon S3 桶上的桶策略。这些 Node.js 模块使用 SDK for JavaScript，通过 Amazon S3 客户端类的以下方法来配置选定的 Amazon S3 桶的策略：
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketPolicy-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#getBucketPolicy-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketPolicy-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putBucketPolicy-property)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteBucketPolicy-property](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#deleteBucketPolicy-property)

有关 Amazon S3 桶的桶策略的更多信息，请参阅《Amazon Simple Storage Service 用户指南》**中的[使用桶策略和用户策略](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-iam-policies.html)。

## 先决条件任务
<a name="w2aac20c25c27c15c11"></a>

要设置和运行此示例，您必须先完成以下任务：
+ 安装 Node.js。有关安装 Node.js 的更多信息，请参阅 [Node.js 网站](https://nodejs.org)。
+ 使用用户凭证创建共享配置文件。有关提供共享凭证文件的更多信息，请参阅[从共享凭证文件加载 Node.js 中的凭证](loading-node-credentials-shared.md)。

## 配置 SDK
<a name="s3-example-bucket-policies-configure-sdk"></a>

通过创建全局配置对象然后为代码设置区域，来配置 SDK for JavaScript。在此示例中，区域设置为 `us-west-2`。

```
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the Region 
AWS.config.update({region: 'us-west-2'});
```

## 检索当前存储桶策略
<a name="s3-example-bucket-policies-get-policy"></a>

创建文件名为 `s3_getbucketpolicy.js` 的 Node.js 模块。该模块将获取单个命令行参数，指定需要其策略的存储桶。确保按前面所示配置开发工具包。

创建 `AWS.S3` 服务对象。在调用 `getBucketPolicy` 方法时，您需要传递的唯一参数是所选存储桶的名称。如果桶当前具有策略，该策略在由 Amazon S3 传递到回调函数的 `data` 参数中返回。

如果所选存储桶没有策略，该信息将在 `error` 参数中返回给回调函数。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

var bucketParams = { Bucket: process.argv[2] };
// call S3 to retrieve policy for selected bucket
s3.getBucketPolicy(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else if (data) {
    console.log("Success", data.Policy);
  }
});
```

要运行示例，请在命令行中键入以下内容。

```
node s3_getbucketpolicy.js BUCKET_NAME
```

此示例代码可在 [GitHub 上的此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_getbucketpolicy.js)找到。

## 设置简单存储桶策略
<a name="s3-example-bucket-policies-set-policy"></a>

创建文件名为 `s3_setbucketpolicy.js` 的 Node.js 模块。该模块将获取单个命令行参数，指定需要应用其策略的存储桶。按前面所示配置 SDK。

创建 `AWS.S3` 服务对象。存储桶策略以 JSON 形式指定。首先，创建一个 JSON 对象，该对象包含用于指定策略的所有值，但标识存储桶的 `Resource` 值除外。

格式化策略所需的 `Resource` 字符串，在其中包含所选存储桶的名称。将该字符串插入到 JSON 对象中。准备 `putBucketPolicy` 方法的参数，包括存储桶的名称以及转换为字符串值的 JSON 策略。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

var readOnlyAnonUserPolicy = {
  Version: "2012-10-17",
  Statement: [
    {
      Sid: "AddPerm",
      Effect: "Allow",
      Principal: "*",
      Action: ["s3:GetObject"],
      Resource: [""],
    },
  ],
};

// create selected bucket resource string for bucket policy
var bucketResource = "arn:aws:s3:::" + process.argv[2] + "/*";
readOnlyAnonUserPolicy.Statement[0].Resource[0] = bucketResource;

// convert policy JSON into string and assign into params
var bucketPolicyParams = {
  Bucket: process.argv[2],
  Policy: JSON.stringify(readOnlyAnonUserPolicy),
};

// set the new policy on the selected bucket
s3.putBucketPolicy(bucketPolicyParams, function (err, data) {
  if (err) {
    // display error message
    console.log("Error", err);
  } else {
    console.log("Success", data);
  }
});
```

要运行示例，请在命令行中键入以下内容。

```
node s3_setbucketpolicy.js BUCKET_NAME
```

此示例代码可在 [GitHub 上的此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_setbucketpolicy.js)找到。

## 删除存储桶策略
<a name="s3-example-bucket-policies-delete-policy"></a>

创建文件名为 `s3_deletebucketpolicy.js` 的 Node.js 模块。该模块将获取单个命令行参数，指定需要删除其策略的存储桶。按前面所示配置 SDK。

 创建 `AWS.S3` 服务对象。在调用 `deleteBucketPolicy` 方法时，您需要传递的唯一参数是所选存储桶的名称。

```
// Load the AWS SDK for Node.js
var AWS = require("aws-sdk");
// Set the region
AWS.config.update({ region: "REGION" });

// Create S3 service object
s3 = new AWS.S3({ apiVersion: "2006-03-01" });

var bucketParams = { Bucket: process.argv[2] };
// call S3 to delete policy for selected bucket
s3.deleteBucketPolicy(bucketParams, function (err, data) {
  if (err) {
    console.log("Error", err);
  } else if (data) {
    console.log("Success", data);
  }
});
```

要运行示例，请在命令行中键入以下内容。

```
node s3_deletebucketpolicy.js BUCKET_NAME
```

此示例代码可在 [GitHub 上的此处](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascript/example_code/s3/s3_deletebucketpolicy.js)找到。