You can configure bucket policies to authorize access to resources in a bucket. You can use bucket policies to authorize one or more RAM users or RAM roles that belong to the current Alibaba Cloud account or other Alibaba Cloud accounts to access specific resources in a bucket. You can use the GUI or specify policy statements in the code editor to configure bucket policies for the bucket to accelerate authorization based on your business scenarios.
Usage notes
The owner of a bucket can use the GUI or specify policy statements in the code editor to configure bucket policies for the bucket in the Object Storage Service (OSS) console. Before you specify policy statements to configure bucket policies, you must understand the Action, Resource, and Condition elements in bucket policies. For more information, see RAM policies.
If you select All Accounts (*) that includes anonymous accounts for the Authorized User parameter and do not configure the Condition parameter when you configure a bucket policy, the bucket policy applies to all users except the bucket owner. If you select All Accounts (*) that includes anonymous accounts for the Authorized User parameter and configure the Condition parameter when you configure a bucket policy, the bucket policy takes effect for all users, including the bucket owner.
You can configure multiple bucket policies for a bucket. The total size of the bucket policies cannot exceed 16 KB.
Scenarios
Bucket policies can be used to grant access permissions to users in the following scenarios:
You want to grant permissions to another Alibaba Cloud account or specific users to access or manage resources in a bucket.
You want to grant different permissions, such as read-only, read and write, or full access, to RAM users that belong to the same Alibaba Cloud account to allow the users to access or manage resources in your bucket.
Procedure
Use the OSS console
Method 1: Configure bucket policies by using the GUI
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 Permission Control > Bucket Policy.
On the Bucket Policy tab, click Add in GUI and then click Authorize.
In the Authorize panel, configure the parameters and click OK. The following table describes the parameters.
Parameter
Description
Applied To
Select the resources on which you want to grant other users the access permissions.
Whole Bucket: The bucket policy applies to all resources in the bucket.
Specific Resources: The bucket policy applies only to specific resources in the bucket. You can configure multiple bucket policies for specific resources in a bucket.
Directory-level authorization
To configure a bucket policy to grant users the permissions to access all subdirectories and objects in a directory, add an asterisk (*) after the directory name. For example, to grant users the permissions to access all subdirectories and objects in a directory named abc, enter
abc/*
.Object-level authorization
To configure a bucket policy to grant users the permissions to access a specific object, enter the full path of the object. The full path cannot contain the bucket name. For example, to grant users the permissions to access an object named myphoto.png in the abc directory, enter
abc/myphoto.png
.
Authorized User
Select the type of accounts to which you want to grant the permissions.
All Accounts (*): Select this option if you want to grant all users the permissions to access the specified resources.
RAM User: Select this option if you want to grant the RAM users of the current Alibaba Cloud account the permissions to access the specified resources. Then, select RAM users from the drop-down list. If you want to grant the permissions to multiple RAM users, we recommend that you enter the keywords of the RAM usernames in the search box to perform fuzzy match.
ImportantBefore you select RAM User, make sure that you log on to the OSS console with an Alibaba Cloud account or as a RAM user who has the permissions to manage the bucket and has the ListUsers permission in the RAM console. Otherwise, you cannot view the RAM users of the current Alibaba Cloud account. For more information about how to grant the ListUsers permission to a RAM user, see Grant permissions to a RAM user.
Other Accounts: Select this option if you want to grant other Alibaba Cloud accounts, RAM users, or RAM roles the permissions to access the specified resources.
To grant other Alibaba Cloud accounts or RAM users the permissions to access the specified resources, enter the unique identifiers (UIDs) of the Alibaba Cloud accounts or RAM users.
To grant RAM roles the permissions to access the specified resources, enter the IDs in the following format:
arn:sts::{RoleOwnerUid}:assumed-role/{RoleName}/{RoleSessionName}
. For example, the role is testrole, the UID of the Alibaba Cloud account that owns the role is137918634953xxxx
, and the RoleSessionName that is specified is testsession. In this case, enterarn:sts::137918634953xxxx:assumed-role/testrole/testsession
. To grant all RAM roles the permissions to access the specified resources, use asterisks (*) as wildcard characters. For example, enterarn:sts::*:*/*/*
. For more information, see AssumeRole.
ImportantIf you grant a RAM role the permissions to access your OSS resources, the RAM role cannot access your OSS resources by using the OSS console. However, the RAM role can access your OSS resources by using ossutil, the OSS API, or OSS SDKs. For example, when you use ossutil to access authorized resources, you must configure access credentials and request OSS resources to check whether the bucket policy takes effect. For more information, see Use the temporary access credentials obtained from STS to access data.
Authorized Operation
You can use one of the following methods to specify authorized operations: Basic Settings and Advanced Settings.
Basic Settings
If you select this option, configure the following permissions based on your business requirements. You can move the pointer over the icon to the right side of each permission to view the actions that correspond to the permission.
Read-Only (excluding ListObject): allows authorized users to view and download the specified resources.
Read-Only (including ListObject): allows authorized users to view, list, and download the specified resources.
Read/Write: allows authorized users to read and write the specified resources.
Full Access: allows authorized users to perform all operations on the specified resources.
Deny Access: forbids authorized users from performing operations on the specified resources.
ImportantTo maintain access to the
.dlsdata/
directory and objects in the directory, do not select Deny Access for Authorized Operation when you configure a bucket policy for a bucket for which OSS-HDFS is enabled.If multiple bucket policies are configured for a user, the user has all the permissions configured in the policies. However, if a bucket policy exists in which the Authorized Operation parameter is set to Deny Access, this bucket policy takes precedence. For example, if you configure a first bucket policy in which Authorized Operation is set to Read-Only and configure a second bucket policy in which Authorized Operation is set to Read/Write, the Read/Write permissions are granted to the user. If you configure a third bucket policy in which Authorized Operation is set to Deny Access, the user is denied access to the resources.
The authorization effect for Read-Only (excluding ListObject), Read-Only (including ListObject), Read/Write, and Full Access is Allow, and the authorization effect for Deny Access is Reject.
Advanced Settings
If you select this option, configure the following parameters:
Effect: Select Allow or Reject.
Actions: Specify the actions that you want to allow or deny. For more information about the supported types of actions, see RAM policies.
Condition (optional)
You can configure this parameter in Basic Settings and Advanced Settings to specify the conditions that must be met before users can access OSS resources.
Access Method: By default, authorized users can access OSS resources over HTTP and HTTPS. If you want authorized users to access the specified resources in the bucket over HTTPS, select HTTPS. If you want authorized users to access the specified resources in the bucket over HTTP, select HTTP. Compared with HTTP, HTTPS is more secure.
If you want to force all requests to access resources in the bucket by using one protocol, such as HTTPS, you must configure the bucket policy by specifying policy statements. For more information, see How do I configure an HTTPS request and an SSL certificate?
IP =: Specify the IP addresses or CIDR blocks that can be used to access OSS resources. Separate multiple IP addresses with commas (,).
IP ≠: Specify the IP addresses or CIDR blocks that cannot be used to access OSS resources. Separate multiple IP addresses with commas (,).
VPC =: Specify the IDs of the VPCs over which users can access OSS resources. You can select the IDs of the VPCs that belong to the current Alibaba Cloud account from the drop-down list. You can also enter the IDs of the VPCs created by using the current Alibaba Cloud account or another Alibaba Cloud account in the field. For information about how to create a VPC, see Create and manage a VPC.
VPC ≠: Specify the IDs of the VPCs over which users cannot access OSS resources. You can select the IDs of the VPCs that belong to the current Alibaba Cloud account from the drop-down list. You can also enter the IDs of the VPCs created by using the current Alibaba Cloud account or another Alibaba Cloud account in the field. For information about how to create a VPC, see Create and manage a VPC.
NoteIf you specify both the VPC (VPC = or VPC ≠) and IP (IP = or IP ≠) conditions in a bucket policy, the bucket policy must meet both the specified VPC and IP address requirements.
Click OK.
Method 2: Configure bucket policies by specifying policy statements
In the left-side navigation tree, choose Permission Control > Bucket Policy.
On the Bucket Policy tab, click Add by Syntax and then click Edit.
In the code editor, enter the bucket policy.
To achieve fine-grained access control, you can specify policy statements based on your business requirements. The following sample code provides examples on how the resource owner whose UID is
174649585760xxxx
configures bucket policies in various scenarios:Example 1: Allow all users to list all objects in a bucket named examplebucket.
{ "Statement": [ { "Action": [ "oss:ListObjects", "oss:ListObjectVersions" ], "Effect": "Allow", "Principal": [ "*" ], "Resource": [ "acs:oss:*:174649585760xxxx:examplebucket" ] }, ], "Version": "1" }
Example 2: Deny all users whose IP addresses are not in the
192.168.0.0/16
CIDR block from managing a bucket named examplebucket.{ "Version": "1", "Statement": [ { "Effect": "Deny", "Action": "oss:*", "Principal": [ "*" ], "Resource": [ "acs:oss:*:174649585760xxxx:examplebucket" ], "Condition":{ "NotIpAddress": { "acs:SourceIp": ["192.168.0.0/16"] } } } ] }
Example 3: Allow a RAM user whose UID is
20214760404935xxxx
to read only thehangzhou/2020
andhangzhou/2015
directories in a bucket named examplebucket.{ "Statement": [ { "Action": [ "oss:GetObject", "oss:GetObjectAcl", "oss:GetObjectVersion", "oss:GetObjectVersionAcl" ], "Effect": "Allow", "Principal": [ "20214760404935xxxx" ], "Resource": [ "acs:oss:*:174649585760xxxx:examplebucket/hangzhou/2020/*", "acs:oss:*:174649585760xxxx:examplebucket/hangzhou/2015/*" ] }, { "Action": [ "oss:ListObjects", "oss:ListObjectVersions" ], "Condition": { "StringLike": { "oss:Prefix": [ "hangzhou/2020/*", "hangzhou/2015/*" ] } }, "Effect": "Allow", "Principal": [ "20214760404935xxxx" ], "Resource": [ "acs:oss:*:174649585760xxxx:examplebucket" ] } ], "Version": "1" }
Click Save. In the message that appears, click OK.
Use ossbrowser
You can use ossbrowser to perform the same bucket-level operations that you can perform in the OSS console. Follow the on-screen instructions in ossbrowser to modify bucket policies. For more information about how to use ossbrowser, see Use ossbrowser.
Use OSS SDKs
The following sample code provides examples on how to configure bucket policies by using OSS SDKs for common programming languages. For more information about how to configure bucket policies by using OSS SDKs for other programming languages, see Overview.
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;
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";
// Create an OSSClient instance.
OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
try {
// In the following example, the bucket owner whose UID is 174649585760xxxx uses a bucket policy to authorize a RAM user whose UID is 20214760404935xxxx to list all objects in the examplebucket bucket.
String policyText = "{\"Statement\": [{\"Effect\": \"Allow\", \"Action\": [\"oss:GetObject\", \"oss:ListObjects\"], \"Principal\": [\"20214760404935xxxx\"], \"Resource\": [\"acs:oss:*:174649585760xxxx:examplebucket/*\"]}], \"Version\": \"1\"}";
// Configure the bucket policy.
ossClient.setBucketPolicy(bucketName, policyText);
} 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 = "https://oss-cn-hangzhou.aliyuncs.com";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
// In the following example, the bucket owner whose UID is 174649585760xxxx uses a bucket policy to authorize a RAM user whose UID is 20214760404935xxxx to list all objects in the examplebucket bucket.
$policy = <<< BBBB
{
"Version":"1",
"Statement":[
{
"Action":[
"oss:GetObject",
"oss:ListObjects"
],
"Principal": [
"20214760404935xxxx"
],
"Effect":"Allow",
"Resource":["acs:oss:*:174649585760xxxx:examplebucket/*"]
}
]
}
BBBB;
try {
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
);
$ossClient = new OssClient($config);
// Configure the bucket policy.
$ossClient->putBucketPolicy($bucket, $policy);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
const OSS = require('ali-oss')
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',
// 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.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
// Specify the name of the bucket. Example: examplebucket.
bucket: 'examplebucket'
});
// In the following example, the bucket owner whose UID is 174649585760xxxx uses a bucket policy to authorize a RAM user whose UID is 20214760404935xxxx to list all objects in the examplebucket bucket.
const policy = {
Version: '1',
Statement: [
{
Action: ['oss:ListObjects', 'oss:GetObject'],
Effect: 'Allow',
Principal: ['20214760404935xxxx'],
Resource: ['acs:oss:*:174649585760xxxx:examplebucket']
}
]
};
async function putPolicy() {
const result = await client.putBucketPolicy('examplebucket', policy);
console.log(result)
}
putPolicy()
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import json
# 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.ProviderAuth(EnvironmentVariableCredentialsProvider())
# In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint.
# Specify the name of the bucket.
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# In the following example, the bucket owner whose UID is 174649585760xxxx uses a bucket policy to authorize a RAM user whose UID is 20214760404935xxxx to list all objects in the examplebucket bucket.
policy_text = '{"Statement": [{"Effect": "Allow", "Action": ["oss:GetObject", "oss:ListObjects"], "Principal": ["20214760404935xxxx"], "Resource": ["acs:oss:*:174649585760xxxx:examplebucket/*"]}], "Version": "1"}'
# Configure the bucket policy.
bucket.put_bucket_policy(policy_text)
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.
var bucketName = "examplebucket";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
// In the following example, the bucket owner whose UID is 174649585760xxxx uses a bucket policy to authorize a RAM user whose UID is 20214760404935xxxx to list all objects in the examplebucket bucket.
string policy = "{\"Version\":\"1\",\"Statement\":[{\"Action\":[\"oss:ListObjects\",\"oss:GetObject\"], \"Principal": \"20214760404935xxxx"\, \"Resource\": \"acs:oss:*:174649585760xxxx:examplebucket\*",\"Effect\": \"Allow\"}]}\n";
var request = new SetBucketPolicyRequest(bucketName, policy);
client.SetBucketPolicy(request);
Console.WriteLine("Set bucket:{0} Policy succeeded ", bucketName);
}
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);
}
package main
import (
"fmt"
"os"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func main() {
// Obtain access credentials from environment variables. Before you run the code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
provider, err := oss.NewEnvironmentVariableCredentialsProvider()
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// Create an OSSClient instance.
// 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. Specify your actual endpoint.
client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// In the following example, the bucket owner whose UID is 174649585760xxxx uses a bucket policy to authorize a RAM user whose UID is 20214760404935xxxx to list all objects in the examplebucket bucket.
policyConfig := `
{
"Statement": [
{
"Action": [
"oss:GetObject",
"oss:ListObjects"
],
"Principal": [
"20214760404935xxxx"
],
"Effect" : "Allow",
"Resource" : ["acs:oss:*:174649585760xxxx:examplebucket/*"]
}
],
"Version": "1"
}`
// Configure the bucket policy.
err = client.SetBucketPolicy("examplebucket", policyConfig)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
fmt.Println("SetBucketPolicy success")
}
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;
int main(void)
{
/* Initialize the 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 name of the bucket. Example: examplebucket. */
std::string BucketName = "examplebucket";
/* Initialize resources, such as network resources. */
InitializeSdk();
ClientConfiguration conf;
/* 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);
/* In the following example, the bucket owner whose UID is 174649585760xxxx uses a bucket policy to authorize a RAM user whose UID is 20214760404935xxxx to list all objects in the examplebucket bucket. */
std::string policy =
R"(
{
"Statement": [
{
"Action": [
"oss:GetObject",
"oss:ListObjects"
],
"Principal": [
"20214760404935xxxx"
],
"Effect" : "Allow",
"Resource" : ["acs:oss:*:174649585760xxxx:examplebucket/*"]
}
],
"Version": "1"
}
)";
SetBucketPolicyRequest request(BucketName);
request.setPolicy(policy);
auto outcome = client.SetBucketPolicy(request);
if (!outcome.isSuccess()) {
/* Handle exceptions. */
std::cout << "Set Bucket Policy fail" <<
",code:" << outcome.error().Code() <<
",message:" << outcome.error().Message() <<
",requestId:" << outcome.error().RequestId() << std::endl;
}
/* Release resources, such as network resources. */
ShutdownSdk();
return 0;
}
Use ossutil
You can use ossutil to configure or modify bucket policies. For more information, see bucket-policy.
Use the OSS API
If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information, see PutBucketPolicy.
Methods to access authorized OSS resources
After you configure a bucket policy for a bucket, you can use one of the following methods to access the resources specified in the bucket policy:
Object URLs (only if all users are authorized to access the resources)
Enter the URL of an object specified in the policy in a browser to access the object. The URL of the object consists of the default domain name of the bucket or a custom domain name mapped to the bucket and the path of the object. Example:
http://mybucket.oss-cn-beijing.aliyuncs.com/file/myphoto.png
. For more information, see OSS domain names.OSS console
Log on to the OSS console. In the left-side navigation pane, click the + icon to the right of Favorite Paths. In the Add Favorite Paths dialog box, add the bucket and the object path specified in the bucket policy. For more information, see OSS access paths.
ossutil
Use the authorized account that is specified in the bucket policy to log on to ossutil to access the resources specified in the policy. For more information, see ossutil.
ossbrowser
Use the authorized account that is specified in the bucket policy to log on to ossbrowser. Enter the path of the object specified in the policy in the Preset OSS Path field. For more information, see ossbrowser.
OSS SDK
You can use OSS SDKs for the following programming languages to access the resources that are specified in the policy: Java, PHP, Node.js, Python, Browser.js, .NET, Android, Go, iOS, C++, and C.