将 PutBucketAcl 与 Amazon SDK 或命令行工具结合使用 - Amazon Simple Storage Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

PutBucketAcl 与 Amazon SDK 或命令行工具结合使用

以下代码示例演示如何使用 PutBucketAcl

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

/// <summary> /// Creates an Amazon S3 bucket with an ACL to control access to the /// bucket and the objects stored in it. /// </summary> /// <param name="client">The initialized client object used to create /// an Amazon S3 bucket, with an ACL applied to the bucket. /// </param> /// <param name="region">The AWS Region where the bucket will be created.</param> /// <param name="newBucketName">The name of the bucket to create.</param> /// <returns>A boolean value indicating success or failure.</returns> public static async Task<bool> CreateBucketUseCannedACLAsync(IAmazonS3 client, S3Region region, string newBucketName) { try { // Create a new Amazon S3 bucket with Canned ACL. var putBucketRequest = new PutBucketRequest() { BucketName = newBucketName, BucketRegion = region, CannedACL = S3CannedACL.LogDeliveryWrite, }; PutBucketResponse putBucketResponse = await client.PutBucketAsync(putBucketRequest); return putBucketResponse.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Amazon S3 error: {ex.Message}"); } return false; }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 PutBucketAcl

C++
适用于 C++ 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

bool AwsDoc::S3::PutBucketAcl(const Aws::String &bucketName, const Aws::String &ownerID, const Aws::String &granteePermission, const Aws::String &granteeType, const Aws::String &granteeID, const Aws::Client::ClientConfiguration &clientConfig, const Aws::String &granteeDisplayName, const Aws::String &granteeEmailAddress, const Aws::String &granteeURI) { Aws::S3::S3Client s3_client(clientConfig); Aws::S3::Model::Owner owner; owner.SetID(ownerID); Aws::S3::Model::Grantee grantee; grantee.SetType(SetGranteeType(granteeType)); if (!granteeEmailAddress.empty()) { grantee.SetEmailAddress(granteeEmailAddress); } if (!granteeID.empty()) { grantee.SetID(granteeID); } if (!granteeDisplayName.empty()) { grantee.SetDisplayName(granteeDisplayName); } if (!granteeURI.empty()) { grantee.SetURI(granteeURI); } Aws::S3::Model::Grant grant; grant.SetGrantee(grantee); grant.SetPermission(SetGranteePermission(granteePermission)); Aws::Vector<Aws::S3::Model::Grant> grants; grants.push_back(grant); Aws::S3::Model::AccessControlPolicy acp; acp.SetOwner(owner); acp.SetGrants(grants); Aws::S3::Model::PutBucketAclRequest request; request.SetAccessControlPolicy(acp); request.SetBucket(bucketName); Aws::S3::Model::PutBucketAclOutcome outcome = s3_client.PutBucketAcl(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &error = outcome.GetError(); std::cerr << "Error: PutBucketAcl: " << error.GetExceptionName() << " - " << error.GetMessage() << std::endl; } else { std::cout << "Successfully added an ACL to the bucket '" << bucketName << "'." << std::endl; } return outcome.IsSuccess(); } //! Routine which converts a human-readable string to a built-in type enumeration. /*! \sa SetGranteePermission() \param access Human readable string. */ Aws::S3::Model::Permission SetGranteePermission(const Aws::String &access) { if (access == "FULL_CONTROL") return Aws::S3::Model::Permission::FULL_CONTROL; if (access == "WRITE") return Aws::S3::Model::Permission::WRITE; if (access == "READ") return Aws::S3::Model::Permission::READ; if (access == "WRITE_ACP") return Aws::S3::Model::Permission::WRITE_ACP; if (access == "READ_ACP") return Aws::S3::Model::Permission::READ_ACP; return Aws::S3::Model::Permission::NOT_SET; } //! Routine which converts a human-readable string to a built-in type enumeration. /*! \sa SetGranteeType() \param type Human readable string. */ Aws::S3::Model::Type SetGranteeType(const Aws::String &type) { if (type == "Amazon customer by email") return Aws::S3::Model::Type::AmazonCustomerByEmail; if (type == "Canonical user") return Aws::S3::Model::Type::CanonicalUser; if (type == "Group") return Aws::S3::Model::Type::Group; return Aws::S3::Model::Type::NOT_SET; }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 PutBucketAcl

CLI
Amazon CLI

此示例向两个 Amazon 用户(user1@example.comuser2@example.com)授予 full control 权限,并向所有人授予 read 权限:

aws s3api put-bucket-acl --bucket MyBucket --grant-full-control emailaddress=user1@example.com,emailaddress=user2@example.com --grant-read uri=http://acs.amazonaws.com/groups/global/AllUsers

有关自定义 ACL(s3api ACL 命令(如 put-bucket-acl)使用相同的速记参数表示法)的详细信息,请参阅 http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUTacl.html。

  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 PutBucketAcl

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.AccessControlPolicy; import software.amazon.awssdk.services.s3.model.Grant; import software.amazon.awssdk.services.s3.model.Permission; import software.amazon.awssdk.services.s3.model.PutBucketAclRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.Type; import java.util.ArrayList; import java.util.List; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class SetAcl { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <id>\s Where: bucketName - The Amazon S3 bucket to grant permissions on.\s id - The ID of the owner of this bucket (you can get this value from the AWS Management Console). """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; String id = args[1]; System.out.format("Setting access \n"); System.out.println(" in bucket: " + bucketName); Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); setBucketAcl(s3, bucketName, id); System.out.println("Done!"); s3.close(); } public static void setBucketAcl(S3Client s3, String bucketName, String id) { try { Grant ownerGrant = Grant.builder() .grantee(builder -> builder.id(id) .type(Type.CANONICAL_USER)) .permission(Permission.FULL_CONTROL) .build(); List<Grant> grantList2 = new ArrayList<>(); grantList2.add(ownerGrant); AccessControlPolicy acl = AccessControlPolicy.builder() .owner(builder -> builder.id(id)) .grants(grantList2) .build(); PutBucketAclRequest putAclReq = PutBucketAclRequest.builder() .bucket(bucketName) .accessControlPolicy(acl) .build(); s3.putBucketAcl(putAclReq); } catch (S3Exception e) { e.printStackTrace(); System.exit(1); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 PutBucketAcl

JavaScript
SDK for JavaScript (v3)
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

放置存储桶 ACL。

import { PutBucketAclCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); // Most Amazon S3 use cases don't require the use of access control lists (ACLs). // We recommend that you disable ACLs, except in unusual circumstances where // you need to control access for each object individually. // Consider a policy instead. For more information see https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucket-policies.html. export const main = async () => { // Grant a user READ access to a bucket. const command = new PutBucketAclCommand({ Bucket: "test-bucket", AccessControlPolicy: { Grants: [ { Grantee: { // The canonical ID of the user. This ID is an obfuscated form of your AWS account number. // It's unique to Amazon S3 and can't be found elsewhere. // For more information, see https://docs.aws.amazon.com/AmazonS3/latest/userguide/finding-canonical-user-id.html. ID: "canonical-id-1", Type: "CanonicalUser", }, // One of FULL_CONTROL | READ | WRITE | READ_ACP | WRITE_ACP // https://docs.aws.amazon.com/AmazonS3/latest/API/API_Grant.html#AmazonS3-Type-Grant-Permission Permission: "FULL_CONTROL", }, ], Owner: { ID: "canonical-id-2", }, }, }); try { const response = await client.send(command); console.log(response); } catch (err) { console.error(err); } };
Kotlin
适用于 Kotlin 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

suspend fun setBucketAcl(bucketName: String, idVal: String) { val myGrant = Grantee { id = idVal type = Type.CanonicalUser } val ownerGrant = Grant { grantee = myGrant permission = Permission.FullControl } val grantList = mutableListOf<Grant>() grantList.add(ownerGrant) val ownerOb = Owner { id = idVal } val acl = AccessControlPolicy { owner = ownerOb grants = grantList } val request = PutBucketAclRequest { bucket = bucketName accessControlPolicy = acl } S3Client { region = "us-east-1" }.use { s3 -> s3.putBucketAcl(request) println("An ACL was successfully set on $bucketName") } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 PutBucketAcl

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

class BucketWrapper: """Encapsulates S3 bucket actions.""" def __init__(self, bucket): """ :param bucket: A Boto3 Bucket resource. This is a high-level resource in Boto3 that wraps bucket actions in a class-like structure. """ self.bucket = bucket self.name = bucket.name def grant_log_delivery_access(self): """ Grant the AWS Log Delivery group write access to the bucket so that Amazon S3 can deliver access logs to the bucket. This is the only recommended use of an S3 bucket ACL. """ try: acl = self.bucket.Acl() # Putting an ACL overwrites the existing ACL. If you want to preserve # existing grants, append new grants to the list of existing grants. grants = acl.grants if acl.grants else [] grants.append( { "Grantee": { "Type": "Group", "URI": "http://acs.amazonaws.com/groups/s3/LogDelivery", }, "Permission": "WRITE", } ) acl.put(AccessControlPolicy={"Grants": grants, "Owner": acl.owner}) logger.info("Granted log delivery access to bucket '%s'", self.bucket.name) except ClientError: logger.exception("Couldn't add ACL to bucket '%s'.", self.bucket.name) raise
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 PutBucketAcl

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。