Amazon Simple Storage Service
Developer Guide (API Version 2006-03-01)
Print this pageEmail this pageGo to the ForumsView the PDFShare this page on TwitterShare this page on FacebookBookmark this page on DeliciousSubmit this page to RedditSubmit this page to DiggDid this page help you?  Yes  No   Tell us about it...

Managing ACLs Using the AWS SDK for .NET

The following tasks guide you through using the C# classes to update ACL on an existing bucket.

Updating ACL on Existing Bucket

1

Create an instance of the AmazonS3 class by providing your AWS credentials.

2

Execute the AmazonS3.GetAcl method to read the existing ACL. You need to provide the resource information, BucketName (if retrieving a bucket ACL) or BucketName and Key name (if retrieving the object ACL). You provide this information using the GetACLRequest object. From the GetACLResponse response, read the S3AccessControlList.

3

To add a grant, execute the S3AccessControlList.AddGrant method by providing the Grantee and the permission values. Before adding new grants, you can optionally clear all the existing grants by calling the S3AccessControlList.Grants.Clear(). Note that this removes all grants including permissions granted to owner. If you clear all the grants, you should regrant the full control grant to the owner.

4

Upload the updated ACL by calling the AmazonS3.SetAcl method. Again, you need to provide the resource information, BucketName (if updating a bucket ACL) or BucketName and Key name (if updating the object ACL using SetACLRequest object).


The following C# code sample demonstrates the preceding tasks. The code sample retrieves an existing bucket ACL, adds new grants to it, and saves the updated ACL.

// Get ACL.
GetACLRequest getRequest = new GetACLRequest(); 
getRequest.BucketName = bucketName;
getRequest.Key = "objectkey";
GetACLResponse getResponse = client.GetACL(getRequest);
S3AccessControlList acl = getResponse.AccessControlList;
getResponse.Dispose();

// Grant permission using email.
S3Grantee grantee1 = new S3Grantee();
grantee1.EmailAddress = "*** Email Address ***";
 acl.AddGrant(grantee1, S3Permission.WRITE_ACP);
   
// Grant permission using Canonical ID.
S3Grantee grantee2 = new S3Grantee();
Amazon.S3.Model.Tuple<string, string> t = 
         new Amazon.S3.Model.Tuple<string, string>
                ("*** canonical user ID ***", "*** Display Name ***");
grantee2.CanonicalUser = t;
acl.AddGrant(grantee2, S3Permission.WRITE);

// Grant permission to the LogDelivery group.
S3Grantee grantee3 = new S3Grantee();
grantee3.URI = "http://acs.amazonaws.com/groups/s3/LogDelivery";
acl.AddGrant(grantee3, S3Permission.WRITE);

// 1. Now update the ACL.
SetACLRequest request = new SetACLRequest();
request.BucketName = bucketName; 
request.ACL = acl;

SetACLResponse response = client.SetACL(request);
response.Dispose();

You can specify a canned ACL (see Canned ACL) when creating a resource. The following C# code sample creates a bucket and specifies a public-read canned ACL in the x-amz-acl request header.

PutBucketRequest request = new PutBucketRequest();
request.WithBucketName(bucketName)
     .WithBucketRegion(S3Region.US);
// Add canned acl.
request.AddHeaders(AmazonS3Util.CreateHeaderEntry(
    "x-amz-acl", "public-read"));

client.PutBucket(request).Dispose();

Example

The following C# code example first creates a bucket. In the request, it specifies a log-delivery-write canned ACL, granting write permission to the LogDelivery group. It then reads the ACL, cleans existing grants, and adds several grants to AWS accounts—using email, canonical user ID, and existing Amazon S3 groups.

using System;
using System.Configuration;
using System.Collections.Specialized;
using Amazon.S3;
using Amazon.S3.Model;
using Amazon.S3.Util;

namespace s3.amazon.com.docsamples.addbucketacl
{
    class S3Sample
    {
        static string bucketName = "*** Provide Bucket Name ***"; 
        static AmazonS3 client;

        public static void Main(string[] args)
        {
            if (checkRequiredFields())
            {
                NameValueCollection appConfig =
                    ConfigurationManager.AppSettings;

                string accessKeyID = appConfig["AWSAccessKey"];
                string secretAccessKeyID = appConfig["AWSSecretKey"];

                using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(
                    accessKeyID, secretAccessKeyID))
                {
                    // Add bucket (specify canned ACL).
                    AddBucketWithCannedACL();

                    // Get ACL on a bucket.
                    GetBucketACL(bucketName); 

                    // Add (replace) ACL on a bucket.
                    AddACLToExistingBucket();
                }
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        static void GetBucketACL(string bucketName)
        {
            try
            {
                // 1. Get ACL request
                GetACLRequest request = new GetACLRequest();
                request.WithBucketName(bucketName);

                GetACLResponse response = client.GetACL(request);
                S3AccessControlList accessControlList = 
                                        response.AccessControlList;
                response.Dispose();
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                    ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    Console.WriteLine("Check the provided AWS Credentials.");
                    Console.WriteLine(
                        "For service sign up go to http://aws.amazon.com/s3");
                }
                else
                {
                    Console.WriteLine(
                        "Error occurred. Message:'{0}' when writing an object"
                        , amazonS3Exception.Message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }

        static void AddBucketWithCannedACL()
        {
            try
            {
                // 1. Create bucket request
                PutBucketRequest request = new PutBucketRequest();
                request.WithBucketName(bucketName)
                    .WithBucketRegion(S3Region.US);
                // add canned acl
                request.AddHeaders(AmazonS3Util.CreateHeaderEntry(
                                               "x-amz-acl", "log-delivery-write"));

                client.PutBucket(request).Dispose();
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                    ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    Console.WriteLine("Check the provided AWS Credentials.");
                    Console.WriteLine(
                        "For service sign up go to http://aws.amazon.com/s3");
                }
                else
                {
                    Console.WriteLine(
                        "Error occurred. Message:'{0}' when writing an object"
                        , amazonS3Exception.Message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }

        static void AddACLToExistingBucket()
        {
            try
            {
                // Get ACL.
                GetACLRequest getRequest = new GetACLRequest(); 
                getRequest.BucketName = bucketName;
                getRequest.Key = "objectkey";
                GetACLResponse getResponse = client.GetACL(getRequest);
                S3AccessControlList acl = getResponse.AccessControlList;
               // S3AccessControlList acl = client.GetACL(getRequest).AccessControlList;
                getResponse.Dispose();

                // Clear existing grants.
                acl.Grants.Clear();

                // Add grants. First, reset owner's full permission.
                S3Grantee grantee0 = new S3Grantee();
                grantee0.WithCanonicalUser(acl.Owner.Id, acl.Owner.DisplayName);
                acl.AddGrant(grantee0, S3Permission.FULL_CONTROL);

                // Grant permission using email.
                S3Grantee grantee1 = new S3Grantee();
                grantee1.EmailAddress = "user@amazon.com";
                acl.AddGrant(grantee1, S3Permission.WRITE_ACP);
   
                // Grant permission using Canonical ID.
                S3Grantee grantee2 = new S3Grantee();
                Amazon.S3.Model.Tuple<string, string> t = 
                    new Amazon.S3.Model.Tuple<string, string>
                        ("f30716ab7115dcb44a5ef76e9d74b8e20567f63b38c4ba23a47fc05cc442d6aa", "display-name");
                grantee2.CanonicalUser = t;
                acl.AddGrant(grantee2, S3Permission.WRITE);

                // Grant permission to the LogDelivery group.
                S3Grantee grantee3 = new S3Grantee();
                grantee3.URI = "http://acs.amazonaws.com/groups/s3/LogDelivery";
                acl.AddGrant(grantee3, S3Permission.WRITE);

                // Grant permission to the AuthenticatedUser group.
                S3Grantee grantee4 = new S3Grantee();
                grantee4.URI = "http://acs.amazonaws.com/groups/global/AuthenticatedUsers";
                acl.AddGrant(grantee4, S3Permission.WRITE_ACP);


                // Grant permission to the AuthenticatedUser group.
                S3Grantee grantee5 = new S3Grantee();
                grantee5.URI = "http://acs.amazonaws.com/groups/global/AllUsers";
                acl.AddGrant(grantee5, S3Permission.READ_ACP);

                // 1. Now update the ACL.
                SetACLRequest request = new SetACLRequest();
                request.BucketName = bucketName; 
                request.ACL = acl;

                SetACLResponse response = client.SetACL(request);
                response.Dispose();

                // Get and print the updated ACL XML.
                Console.WriteLine(client.GetACL(new GetACLRequest()
                    .WithBucketName(bucketName)).ResponseXml);

            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                    ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    Console.WriteLine("Check the provided AWS Credentials.");
                    Console.WriteLine(
                        "For service sign up go to http://aws.amazon.com/s3");
                }
                else
                {
                    Console.WriteLine(
                        "Error occurred. Message:'{0}' when writing an object"
                        , amazonS3Exception.Message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

        }

        static bool checkRequiredFields()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            if (string.IsNullOrEmpty(appConfig["AWSAccessKey"]))
            {
                Console.WriteLine(
                    "AWSAccessKey was not set in the App.config file.");
                return false;
            }
            if (string.IsNullOrEmpty(appConfig["AWSSecretKey"]))
            {
                Console.WriteLine(
                    "AWSSecretKey was not set in the App.config file.");
                return false;
            }
            if (string.IsNullOrEmpty(bucketName))
            {
                Console.WriteLine("The variable bucketName is not set.");
                return false;
            }
            /*
            if (string.IsNullOrEmpty(keyName))
            {
                Console.WriteLine("The variable keyName is not set.");
                return false;
            }
            */
            return true;
        }
    }
}