Object ACL provides object-level access control in OSS. Use it to grant read or write permissions on individual objects independent of the bucket ACL. Supported values: public-read-write, public-read, private, and default (inherits bucket ACL).
Usage notes
-
The RAM user must have the
oss:PutObjectAclpermission. For more information, see Grant a custom policy.
-
If you do not configure an object ACL, the object inherits the bucket ACL.
-
An explicitly set object ACL takes precedence over the bucket ACL. For example, a public-read object allows anonymous access regardless of the bucket ACL.
Types of ACLs
OSS supports the following object ACLs.
|
ACL |
Description |
|
public-read-write |
Anyone, including anonymous users, can read and write the object. Warning
This ACL allows all users to access and write data to the object over the Internet, which may cause unauthorized access, unexpected costs, or uploads of prohibited content. Do not set the object ACL to public-read-write unless necessary. |
|
public-read |
Only the object owner can write to the object. All other users, including anonymous users, can only read it. Warning
This may cause unauthorized access and unexpected costs. Exercise caution when using this ACL. |
|
private |
Only the object owner can read and write the object. Other users cannot access it. Note
You can send object URLs to share your private objects with your partners. For more information, see (Recommended) V4 signatures in presigned URLs. |
|
default |
The ACL of the object is the same as that of the bucket in which the object is stored. |
Methods
Use the OSS console
Log on to the OSS console.
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the left-side navigation tree, choose Object Management > Objects.
-
Specify the ACL of an object.
-
Go to the Set ACL panel.
Go to the Set ACL panel by using one of the following methods:
-
Find the object in the object list and click View Details in the Actions column. Then, click Set ACL next to Object ACL.
-
Find the object in the object list and choose
> Set ACL in the Actions column.
-
-
In the Set ACL panel, configure the ACL based on your business requirements.
-
-
Click OK.
Use ossbrowser
ossbrowser supports the same object-level operations as the OSS console. Follow the on-screen instructions to modify the object ACL. For more information, see Common operations.
Use OSS SDKs
The following examples show how to modify object ACL using OSS SDKs for common programming languages. For other languages, see Overview.
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
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.
// Call the shutdown method to release associated resources when the OSSClient is no longer in use.
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();
}
}
}
} const oss = require('ali-oss');
const client = oss({
// Set region to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set region to oss-cn-hangzhou.
region: 'yourregion',
// Obtain access credentials from environment variables. Before running the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
authorizationV4: true,
// Set bucket to the name of your bucket.
bucket: 'yourbucketname'
});
async function setACL() {
try {
// Set yourObjectName to the full path of the object. The full path cannot contain the bucket name.
await client.putACL('yourObjectName', 'private');
console.log('Set ACL successfully');
} catch (e) {
console.error(e);
}
}
setACL();<!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 bucket name and the full path of the object. Example: examplebucket and exampledir/exampleobject.txt. The full path of the object cannot contain the bucket name.
GetObjectACLRequest request = new GetObjectACLRequest("examplebucket", "exampledir/exampleobject.txt");
// OSS SDK for Android does not support setting object ACLs. You can only get object ACLs.
// The following code shows how to get 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) {
// Request exceptions.
if (clientException != null) {
// Client exceptions, such as network exceptions.
clientException.printStackTrace();
}
if (serviceException != null) {
// Server 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 OSS account information. */
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
std::string Endpoint = "yourEndpoint";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
std::string Region = "yourRegion";
/* Specify the bucket name. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Specify the full path of the object. The full path cannot include the bucket name. Example: exampledir/exampleobject.txt. */
std::string ObjectName = "exampledir/exampleobject.txt";
/* Initialize network resources. */
InitializeSdk();
ClientConfiguration conf;
conf.signatureVersion = SignatureVersionType::V4;
/* Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
OssClient client(Endpoint, credentialsProvider, conf);
client.SetRegion(Region);
/* Set the object access permissions. */
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 network resources. */
ShutdownSdk();
return 0;
}#include "oss_api.h"
#include "aos_http_io.h"
/* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Specify the bucket name. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the object. The full path cannot contain the bucket name. Example: exampledir/exampleobject.txt. */
const char *object_name = "exampledir/exampleobject.txt";
/* Set yourRegion to the region where the bucket is located. For example, if the bucket is 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);
/* Initialize an aos_string_t type with a char* string. */
aos_str_set(&options->config->endpoint, endpoint);
/* Obtain access credentials from environment variables. Before you run this 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"));
// The following two parameters also need to be configured.
aos_str_set(&options->config->region, region);
options->config->signature_version = 4;
/* Specify whether a CNAME is used. 0 indicates that no CNAME is used. */
options->config->is_cname = 0;
/* Set 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 at the program entrance to initialize global resources such as the network and memory. */
if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
exit(1);
}
/* The memory pool (pool) is used for memory management and is equivalent to apr_pool_t. The implementation code is in the apr library. */
aos_pool_t *pool;
/* Create a new memory pool. The second parameter is NULL, which indicates that the new memory pool does not inherit from another memory pool. */
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 memory to options in the memory pool. */
oss_client_options = oss_request_options_create(pool);
/* Initialize the client options oss_client_options. */
init_options(oss_client_options);
/* Initialize 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;
/* Set the object ACL. */
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");
}
/* Get the object ACL. */
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 releases the memory allocated to resources during 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 // The region where the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// The init function is used to initialize command-line parameters.
func init() {
flag.StringVar(®ion, "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 empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configurations and set 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 set 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.
}
// Execute the operation to set the ACL of the object.
putResult, err := client.PutObjectAcl(context.TODO(), putRequest)
if err != nil {
log.Fatalf("failed to put object acl %v", err)
}
// Print the result of setting the object ACL.
log.Printf("put object acl result:%#v\n", putResult)
// Create a request to obtain the ACL (access control list) of the object.
getRequest := &oss.GetObjectAclRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
}
// Execute the operation to obtain the ACL of the object.
getResult, err := client.GetObjectAcl(context.TODO(), getRequest)
if err != nil {
log.Fatalf("failed to get object acl %v", err)
}
// Print the result of obtaining the object ACL.
log.Printf("get object acl result:%#v\n", getResult)
}
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use AlibabaCloud\Oss\V2 as Oss;
$optsdesc = [
"region" => ['help' => 'The region in which the bucket is located.', 'required' => True],
"endpoint" => ['help' => 'The domain names that other services can use to access OSS.', 'required' => False],
"bucket" => ['help' => 'The name of the bucket', 'required' => True],
"key" => ['help' => 'The name of the object', 'required' => True],
];
// Create an array of long options required by getopt. Example: --region:.
$longopts = array_map(function ($key) {
return "$key:";
}, array_keys($optsdesc));
// Parse the command line parameters.
$options = getopt("", $longopts);
// Check whether the required parameters are missing.
foreach ($optsdesc as $key => $value) {
if ($value['required'] === True && empty($options[$key])) {
// Print the help information and exit if required parameters are missing.
$help = $value['help'];
echo "Error: the following arguments are required: --$key, $help\n";
exit(1);
}
}
// Extract the values of the parameters.
$region = $options["region"];
$bucket = $options["bucket"];
$key = $options["key"];
// Obtain access credentials (AccessKey ID and AccessKey secret) from environment variables.
$credentialsProvider = new Oss\Credentials\EnvironmentVariableCredentialsProvider();
// Load the default configurations and specify the credential provider and region.
$cfg = Oss\Config::loadDefault();
$cfg->setCredentialsProvider($credentialsProvider);
$cfg->setRegion($region);
// If the endpoint parameter is specified, it will be configured as the custom access URL.
if (isset($options["endpoint"])) {
$cfg->setEndpoint($options["endpoint"]);
}
// Initialize the OSSClient instance.
$client = new Oss\Client($cfg);
// Create a PutObjectAclRequest object and specify the bucket name, object key and ACL.
$request = new Oss\Models\PutObjectAclRequest($bucket, $key, Oss\Models\ObjectACLType::PUBLIC_READ);
// Set the ACL of the object to public-read.
$result = $client->putObjectAcl($request);
// Output the HTTP status code and request ID from the response.
printf(
'status code:' . $result->statusCode . PHP_EOL .
'request id:' . $result->requestId
);
import argparse
import alibabacloud_oss_v2 as oss
# Create a command-line argument parser.
parser = argparse.ArgumentParser(description="put object acl sample")
# Add required parameters: region, bucket name, object key, and access control list (ACL).
parser.add_argument('--region', help='The region in which the bucket is located.', required=True)
parser.add_argument('--bucket', help='The name of the bucket.', required=True)
parser.add_argument('--endpoint', help='The domain names that other services can use to access OSS')
parser.add_argument('--key', help='The name of the object.', required=True)
parser.add_argument('--acl', help='Specify the access permission ACL for the object.', required=True)
def main():
# Parse command-line arguments.
args = parser.parse_args()
# Load access credential information from environment variables.
credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider()
# Use the default configurations of the SDK.
cfg = oss.config.load_default()
# Set the credential provider.
cfg.credentials_provider = credentials_provider
# Set the region provided by the user.
cfg.region = args.region
# If an endpoint is provided, set the endpoint in the configuration.
if args.endpoint is not None:
cfg.endpoint = args.endpoint
# Create an OSS client.
client = oss.Client(cfg)
# Set the ACL of the object.
result = client.put_object_acl(oss.PutObjectAclRequest(
bucket=args.bucket, # The bucket name.
key=args.key, # The object key.
acl=args.acl, # The new ACL value.
))
# Print the output information after setting the ACL.
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' version id: {result.version_id},'
)
# Obtain and print the current ACL settings of the object.
result = client.get_object_acl(oss.GetObjectAclRequest(
bucket=args.bucket,
key=args.key,
))
print(f'status code: {result.status_code},'
f' request id: {result.request_id},'
f' acl: {result.acl},'
f' version id: {result.version_id},'
)
# Call the main function when this script is run directly.
if __name__ == "__main__":
main()
Use ossutil
Use ossutil to configure or modify object ACLs. For installation instructions, see Install ossutil.
The following example sets the object ACL to private.
ossutil api put-object-acl --bucket examplebucket --key exampleobject --object-acl private
For more information, see put-object-acl.
Related API operation
The methods above are based on the RESTful API, which you can call directly for custom integrations. Direct API calls require signature calculation. For more information, see PutObjectACL.
References
-
To share a private object with other users, see Using presigned URLs to download or preview files.
-
To preview an object when you use a browser to access the object, see How to configure browser preview behavior for OSS objects?.