すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:オブジェクトACL

最終更新日:Feb 17, 2025

オブジェクトのアクセス制御リスト (ACL) を設定することで、object Storage Service (OSS) バケット内の特定のオブジェクトに対して読み取りおよび書き込み権限を付与できます。 オブジェクトACLを使用すると、バケット内の他のオブジェクトのアクセス許可に影響を与えることなく、特定のオブジェクトのアクセス許可を管理できます。 オブジェクトのACLは、public-read、public-read-write、またはprivateです。 ビジネス要件に基づいて、オブジェクトを作成するとき、または既存のオブジェクトのACLを変更するときに、オブジェクトのACLを設定できます。

使用上の注意

  • オブジェクトのACLを設定しない場合は、デフォルトのオブジェクトACLが使用されます。 この場合、オブジェクトのACLは、オブジェクトが格納されているバケットのACLと同じです。

  • オブジェクトACLをバケットACLとは異なる値に設定した場合、オブジェクトACLが優先されます。 たとえば、バケット内のオブジェクトのACLをパブリック読み取りに設定した場合、バケットのACLに関係なく、認証されたリクエストと匿名のリクエストを使用してオブジェクトにアクセスできます。

ACLのタイプ

次の表に、オブジェクトに対して構成できるACLを示します。

ACL

説明

公開読み取り/書き込み

匿名ユーザーを含むすべてのユーザーは、オブジェクトからデータを読み書きできます。

警告

オブジェクトACLをこの値に設定すると、すべてのユーザーがオブジェクトにアクセスし、インターネット経由でオブジェクトにデータを書き込むことができます。 これにより、バケット内のデータへの不正アクセスと高コストが発生する可能性があります。 ユーザーが禁止されているデータまたは情報をバケットにアップロードすると、正当な利益と権利が侵害される可能性があります。 したがって、必要がない限り、バケットのACLをpublic-read-writeに設定しないことをお勧めします。

公開読み取り

オブジェクトにデータを書き込むことができるのは、オブジェクト所有者だけです。 匿名ユーザーを含む他のユーザーは、オブジェクトのみを読み取ることができます。

警告

これにより、バケット内のデータへの不正アクセスと高コストが発生する可能性があります。 オブジェクトACLをpublic-readに設定する場合は注意してください。

非公開

オブジェクト所有者のみが、バケット内のオブジェクトに対してデータを読み書きできます。 他のユーザーはオブジェクトにアクセスできません。

説明

オブジェクトURLを送信して、プライベートオブジェクトをパートナーと共有できます。 詳細については、「URLにV1署名を含める」をご参照ください。

default

オブジェクトのACLは、オブジェクトが格納されているバケットのACLと同じです。

方法

OSSコンソールの使用

  1. OSSコンソールにログインします。

  2. 左側のナビゲーションウィンドウで、バケットリスト をクリックします。 [バケット] ページで、目的のバケットを見つけてクリックします。

  3. 左側のナビゲーションツリーで、ファイル>オブジェクトを選択します。

  4. オブジェクトのACLを指定します。

    1. Set ACLパネルに移動します。

      次のいずれかの方法を使用して、[ACLの設定] パネルに移動できます。

      • オブジェクトリストでオブジェクトを見つけ、[操作] 列の プロパティ をクリックします。 次に、オブジェクトACLの横にある ACLを設定 をクリックします。

      • オブジェクトリストでオブジェクトを見つけ、[操作] 列で more > ACLを設定 を選択します。

    2. ACLを設定パネルで、ビジネス要件に基づいてACLを設定します。

  5. OKをクリックします。

ossbrowserの使用

ossbrowserを使用して、OSSコンソールで実行できるのと同じオブジェクトレベルの操作を実行できます。 ossbrowserの画面上の指示に従って、オブジェクトのACLを変更できます。 詳細については、「ossbrowserの使用」をご参照ください。

OSS SDKの使用

次のサンプルコードは、一般的なプログラミング言語のOSS SDKを使用してオブジェクトのACLを変更する方法の例を示しています。 他のプログラミング言語のOSS SDKを使用してオブジェクトのACLを変更する方法の詳細については、「概要」をご参照ください。

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;

public class Demo {
    public static void main(String[] args) throws Exception {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. Example: testfolder/exampleobject.txt. 
        String objectName = "testfolder/exampleobject.txt";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Set the ACL of the object to public read. 
            ossClient.setObjectAcl(bucketName, objectName, CannedAccessControlList.PublicRead);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}            
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
    require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
use OSS\OssClient;
use OSS\Core\OssException;

// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.  
$provider = new EnvironmentVariableCredentialsProvider();
// In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
$endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
$bucket= "yourBucketName";
$object = "yourObjectName";
// Set the ACL of the object to public-read. If you do not specify the ACL of the object, the ACL of the object inherits the ACL of the bucket in which the object is stored. 
$acl = "public-read";
try {
    $config = array(
        "provider" => $provider,
        "endpoint" => $endpoint,
        "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
        "region"=> "cn-hangzhou"
    );
    $ossClient = new OssClient($config);

    $ossClient->putObjectAcl($bucket, $object, $acl);
} catch (OssException $e) {
    printf(__FUNCTION__ . ": FAILED\n");
    printf($e->getMessage() . "\n");
    return;
}
print(__FUNCTION__ . ": OK" . "\n");
            
const oss = require('ali-oss');

const client = oss({ 
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Specify the name of the bucket. 
  bucket: 'yourbucketname'
});
  
async function setACL() {
  try {
    // Specify the full path of the object. Do not include the bucket name in the full path. 
    await client.putACL('yourObjectName', 'private');
    console.log('Set ACL successfully');
  } catch (e) {
    console.error(e);
  }
}

setACL();
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
endpoint = "https://oss-cn-hangzhou.aliyuncs.com"

# Specify the ID of the region that maps to the endpoint. Example: cn-hangzhou. This parameter is required if you use the signature algorithm V4.
region = "cn-hangzhou"

# Specify the name of your bucket.
bucket = oss2.Bucket(auth, endpoint, "yourBucketName", region=region)

# Specify the full path of the object. Do not include the bucket name in the full path. 
bucket.put_object_acl('yourObjectName', oss2.OBJECT_ACL_PUBLIC_READ)
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <script src="https://gosspublic.alicdn.com/aliyun-oss-sdk-6.18.0.min.js"></script>
    <script>
      const client = new OSS({
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
        region: "yourRegion",
        authorizationV4: true,
        // Specify the temporary AccessKey pair obtained from STS. The AccessKey pair consists of an AccessKey ID and an AccessKey secret. 
        accessKeyId: "yourAccessKeyId",
        accessKeySecret: "yourAccessKeySecret",
        // Specify the security token obtained from STS. 
        stsToken: "yourSecurityToken",
        // Specify the name of the bucket. Example: examplebucket. 
        bucket: "examplebucket",
      });

      async function getACL() {
        try {
          result = await client.getACL("examplefile.txt");
          console.log(result.acl);

          await client.putACL("examplefile.txt", "public-read");
          result = await client.getACL("examplefile.txt");
          console.log(result.acl);
        } catch (e) {
          console.log(e);
        }
      }

      getACL();
    </script>
  </body>
</html>
using Aliyun.OSS;
using Aliyun.OSS.Common;
// Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. 
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket. Example: examplebucket. 
var bucketName = "examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. 
var objectName = "exampleobject.txt";
// Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
const string region = "cn-hangzhou";

// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();

// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;

// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
c.SetRegion(region);
// Configure the ACL of the object. 
try
{
    // Call SetObjectAcl to configure the ACL of the object. 
    client.SetObjectAcl(bucketName, objectName, CannedAccessControlList.PublicRead);
    Console.WriteLine("Set Object:{0} ACL succeeded ", objectName);
}
catch (Exception ex)
{
    Console.WriteLine("Set Object ACL failed with error info: {0}", ex.Message);
}
// Query the ACL of the object. 
try
{
    // Call GetObjectAcl to query the ACL of the object. 
    var result = client.GetObjectAcl(bucketName, objectName);
    Console.WriteLine("Get Object ACL succeeded, Id: {0}  ACL: {1}",
        result.Owner.Id, result.ACL.ToString());
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID: {2}\tHostID: {3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
// Specify the name of the bucket and the full path of the object. In this example, the name of the bucket is examplebucket and the full path of the object is exampledir/exampleobject.txt. Do not include the bucket name in the full path. 
GetObjectACLRequest request = new GetObjectACLRequest("examplebucket", "exampledir/exampleobject.txt");
// You cannot configure the ACL of an object by using OSS SDK for Android. You can only obtain the ACL of an object by using OSS SDK for Android. 
// The following sample code provides an example on how to query the ACL of an object: 
oss.asyncGetObjectACL(request, new OSSCompletedCallback<GetObjectACLRequest, GetObjectACLResult>() {
    @Override
    public void onSuccess(GetObjectACLRequest request, GetObjectACLResult result) {
        Log.d("GetObjectACL", "Success!");
        Log.d("ObjectAcl", result.getObjectACL());
        Log.d("Owner", result.getObjectOwner());
        Log.d("ID", result.getObjectOwnerID());
    }

    @Override
    public void onFailure(GetObjectACLRequest request, ClientException clientException, ServiceException serviceException) {
        // Handle request exceptions. 
        if (clientException != null) {
            // Handle client-side exceptions, such as network errors. 
            clientException.printStackTrace();
        }
        if (serviceException != null) {
            // Handle server-side exceptions. 
            Log.e("ErrorCode", serviceException.getErrorCode());
            Log.e("RequestId", serviceException.getRequestId());
            Log.e("HostId", serviceException.getHostId());
            Log.e("RawMessage", serviceException.getRawMessage());
        }
    }
});
OSSPutObjectACLRequest *request = [OSSPutObjectACLRequest new];
// Specify the name of the bucket. Example: examplebucket. 
request.bucketName = @"examplebucket";
// Specify the full path of the object. Do not include the bucket name in the full path. Example: exampleobject.txt. 
request.objectKey = @"exampleobject.txt";
/**
 * Configure the object ACL. 
 * public-read
 * private
 * public-read-write
 * default
 */
request.acl = @"private";

OSSTask * putObjectACLTask = [client putObjectACL:request];
[putObjectACLTask continueWithBlock:^id(OSSTask *task) {
    if (!task.error) {
        NSLog(@"put object ACL success!");
    } else {
        NSLog(@"put object ACL failed, error: %@", task.error);
    }
    return nil;
}];
// Implement synchronous blocking to wait for the task to complete. 
// [putObjectACLTask waitUntilFinished];
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize information about the account that is used to access OSS. */
            
    /* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Specify the name of the bucket. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the object. Do not include the bucket name in the full path of the object. Example: exampledir/exampleobject.txt. */
    std::string ObjectName = "exampledir/exampleobject.txt";


    /* Initialize resources such as network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Configure the ACL of the object. */
    SetObjectAclRequest request(BucketName, ObjectName);
    request.setAcl(CannedAccessControlList::Private);
    auto outcome = client.SetObjectAcl(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetObjectAcl fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release resources such as network resources. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the name of the bucket. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou. */
const char *region = "yourRegion";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Use a char* string to initialize data of the aos_string_t type. */
    aos_str_set(&options->config->endpoint, endpoint);
    /* Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    aos_str_set(&options->config->access_key_id, getenv("OSS_ACCESS_KEY_ID"));
    aos_str_set(&options->config->access_key_secret, getenv("OSS_ACCESS_KEY_SECRET"));
    // Specify two additional parameters.
    aos_str_set(&options->config->region, region);
    options->config->signature_version = 4;
    /* Specify whether to use CNAME. The value 0 indicates that CNAME is not used. */
    options->config->is_cname = 0;
    /* Specify network parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method in main() to initialize global resources, such as network resources and memory resources. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* Create a memory pool to manage memory. aos_pool_t is equivalent to apr_pool_t. The code used to create a memory pool is included in the APR library. */
    aos_pool_t *pool;
    /* Create a memory pool. The value of the second parameter is NULL. This value indicates that the pool does not inherit other memory pools. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information, such as endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate the memory resources in the memory pool to the options. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize oss_client_options. */
    init_options(oss_client_options);
    /* Initialize the parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_table_t *resp_headers = NULL; 
    aos_status_t *resp_status = NULL; 
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    oss_acl_e oss_acl = OSS_ACL_PRIVATE;
    /* Configure the ACL for the object. */
    resp_status = oss_put_object_acl(oss_client_options, &bucket, &object, oss_acl, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("put object acl success!\n"); 
    } else {
        printf("put object acl failed!\n"); 
    }
    /* Query the ACL of the object. */
    aos_string_t oss_acl_string;
    resp_status = oss_get_object_acl(oss_client_options, &bucket, &object, &oss_acl_string, &resp_headers);
    if (aos_status_is_ok(resp_status)) {
        printf("get object acl success!\n");
        printf("acl: %s \n", oss_acl_string.data);
    } else {
        printf("get object acl failed!\n");
    }
    /* Release the memory pool. This operation releases the memory resources allocated for the request. */
    aos_pool_destroy(pool);
    /* Release the allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
  # In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
  endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
  # Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  access_key_id: ENV['OSS_ACCESS_KEY_ID'],
  access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Specify the name of the bucket. Example: examplebucket. 
bucket = client.get_bucket('examplebucket')
# Specify the full path of the object. Do not include the bucket name in the full path. Example: exampledir/example.txt. 
# Query the object ACL that is specified when the object is uploaded. 
acl = bucket.get_object_acl('exampledir/example.txt')
puts acl
# Modify the object ACL. 
bucket.set_object_acl('exampledir/example.txt', Aliyun::OSS::ACL::PUBLIC_READ)
acl = bucket.get_object_acl('exampledir/example.txt')
puts acl                
package main

import (
	"context"
	"flag"
	"log"

	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
	"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)

// Define global variables.
var (
	region     string // Region in which your bucket is located.
	bucketName string // Name of the bucket.
	objectName string // Name of the object.
)

// Specify the init function used to initialize command line parameters.
func init() {
	flag.StringVar(&region, "region", "", "The region in which the bucket is located.")
	flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
	flag.StringVar(&objectName, "object", "", "The name of the object.")
}

func main() {
	// Parse command line parameters.
	flag.Parse()

	// Check whether the region is specified.
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the name of the bucket is specified.
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the name of the object is specified.
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region.
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	// Create an OSS client.
	client := oss.NewClient(cfg)

	// Create a request to configure the ACL of the object.
	putRequest := &oss.PutObjectAclRequest{
		Bucket: oss.Ptr(bucketName),  // The name of the bucket.
		Key:    oss.Ptr(objectName),  // The name of the object.
		Acl:    oss.ObjectACLPrivate, // Set the ACL of the object to private.
	}

	// Perform the operation to configure the ACL.
	putResult, err := client.PutObjectAcl(context.TODO(), putRequest)
	if err != nil {
		log.Fatalf("failed to put object acl %v", err)
	}

	// Display the result.
	log.Printf("put object acl result:%#v\n", putResult)

	// Create a request to query the ACL.
	getRequest := &oss.GetObjectAclRequest{
		Bucket: oss.Ptr(bucketName), // The name of the bucket.
		Key:    oss.Ptr(objectName), // The name of the object.
	}

	// Perform the query operation.
	getResult, err := client.GetObjectAcl(context.TODO(), getRequest)
	if err != nil {
		log.Fatalf("failed to get object acl %v", err)
	}

	// Display the query result.
	log.Printf("get object acl result:%#v\n", getResult)
}

ossutilの使用

ossutilを使用して、オブジェクトのACLを設定または変更できます。 ossutilのインストールについては、「ossutilのインストール」をご参照ください。

次のコードは、examplebucketのACLをprivateに設定する方法を示しています。

ossutil api put-object-acl --bucket examplebucket --key exampleobject --object-acl private

詳細については、「put-object-acl」をご参照ください。

関連API操作

上記のメソッドは基本的にRESTful APIに基づいて実装されており、ビジネスで高レベルのカスタマイズが必要な場合に直接呼び出すことができます。 APIを直接呼び出すには、コードに署名計算を含める必要があります。 詳細については、「PutObjectACL」をご参照ください。

関連ドキュメント