Object Storage Service (OSS) supports resource-based authorization, which lets you set access policies at the bucket level instead of the user level. You can use a bucket policy to grant one or more Resource Access Management (RAM) users or RAM roles from your Alibaba Cloud account or other Alibaba Cloud accounts access to specified resources in a bucket. You can configure bucket policies using policy syntax or a graphical user interface (GUI). The GUI helps you quickly grant permissions based on your business scenarios.
Notes
By default, an Alibaba Cloud account can configure bucket policies. To configure a bucket policy as a RAM user or using a Security Token Service (STS) token, you must have the
oss:PutBucketPolicy
permission. For more information, see Grant custom access policies to a RAM user.Bucket owners can configure bucket policies in the OSS console using the GUI or policy syntax. Before you configure a bucket policy using policy syntax, you must understand the classifications of OSS actions, resources, and conditions. For more information, see RAM Policy.
When you configure a bucket policy, if you grant permissions to all accounts (*), including anonymous requests, and do not include a condition, the bucket policy applies to all users except the bucket owner. If you grant permissions to all accounts (*) and include a condition, the bucket policy applies to all users, including the bucket owner.
You can add multiple bucket policies. However, the total size of all bucket policies cannot exceed 16 KB. The length of each field in a bucket policy cannot exceed 4,095 bytes.
Scenarios
Bucket policies are typically used for authorization in the following scenarios:
Granting cross-account access or granting a specified user permissions to access or manage an entire bucket or specific resources within the bucket.
Granting different permissions, such as read-only, read/write, or full control, to different RAM users within the same account to access or manage bucket resources.
Configure an authorization policy
Configure a bucket policy for a standard bucket
Console
Method 1: Configure a bucket policy using the GUI
In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.
In the navigation pane on the left, choose Permission Control > Bucket Policy.
On the Bucket Policy page, on the Add in GUI tab, click Authorize.
On the Authorize panel, configure the required parameters and click OK.
Configuration Item
Description
Applied To
Grant other users access to the entire bucket or specific resources within the bucket.
Whole Bucket: The authorization policy applies to the entire bucket.
Specific Resources: The authorization policy applies only to the specified resources. You can configure multiple authorization policies for specified resources.
Grant permissions at the folder level
To grant access to all subdirectories and files in a folder, add a wildcard character (*) to the end of the folder name. For example, to grant access to all subdirectories and files in the abc/ folder, enter
abc/*
.Grant permissions for a specific file
To grant access to a specific file in a folder, enter the full path of the file, excluding the bucket name. For example, to grant access to the myphoto.png file in the abc/ folder, enter
abc/myphoto.png
.
Authorized User
Grant access to resources to different users by selecting different account types.
All Accounts (*): Select this option to grant all users access to the specified resources.
RAM User: Select this option to grant RAM users under the current account access to the specified resources. Then, select the target RAM user from the drop-down list. To grant permissions to many RAM users, you can enter a keyword of the RAM user name in the search box for a fuzzy match.
ImportantYour account must be an Alibaba Cloud account or a RAM user with management permissions for this bucket and the `ListUsers` permission in the RAM console. Otherwise, you cannot view the list of RAM users for the current 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 to grant access to other Alibaba Cloud accounts, RAM users, or RAM roles.
When you grant permissions to another Alibaba Cloud account or RAM user, enter the UID of the authorized account.
When you grant permissions to a RAM role, the format is
arn:sts::{RoleOwnerUid}:assumed-role/{RoleName}/{RoleSessionName}
. For example, if the RAM role is testrole, the UID of the role owner is137918634953xxxx
, and the role session name is testsession. In this case, enterarn:sts::137918634953xxxx:assumed-role/testrole/testsession
. To grant permissions to all RAM roles, use the wildcard character (*). For example, configure it asarn:sts::*:*/*/*
. For more information, see AssumeRole - Obtain temporary identity credentials for a RAM role.
ImportantWhen the authorized object is a RAM role, the account cannot access the authorized resources through the OSS console. You can access the authorized resources using ossutil, an OSS SDK, or the OSS API. For example, to access authorized resources using ossutil, you must configure access credentials by following the instructions in Use a temporary token for access. Then, request the OSS resources to verify that the bucket policy is effective.
Authorized Operation
You can configure authorized operations using Basic Settings and Advanced Settings.
Basic Settings
Select this option. Then, configure the access permissions based on your scenario as described below. Hover the mouse pointer over the
icon next to each access permission to view the list of corresponding actions.
Read-Only (excluding ListObject): View and download related resources.
Read-Only (including ListObject): View, list, and download related resources.
Read/Write: Read and write related resources.
Full Access: All operation permissions for related resources, such as read, write, and delete.
Deny Access: Deny all operations on related resources.
ImportantTo ensure that users of the OSS-Hadoop Distributed File System (HDFS) service can access the .dlsdata/ folder and any object within it, do not set Authorized Operations to Access Denied when configuring a bucket policy for a bucket with OSS-HDFS enabled.
If multiple bucket policy rules are configured for a user, the user's permissions are the sum of all policy rules. If these bucket policies include a deny permission, the deny permission takes precedence. For example, if a user is first granted read-only permission and then read/write permission, the user's final permission is read/write. If the user is then granted access denied permission, the user's final permission is access denied.
The authorization effect for Read-only, Read/Write, and Full Control is Allow. The authorization effect for Access Denied is Deny.
Advanced Settings
Select this option. Then, complete the following configurations.
Effect: Includes two authorization effects: Allow and Deny.
Actions: Supports all actions that OSS supports. For more information about action classifications, see RAM Policy.
Condition (Optional)
You can also select this option in Basic Settings and Advanced Settings modes to restrict access to OSS resources to only users who meet the conditions.
Access Method: By default, HTTP and HTTPS access methods are supported. If you want the current authorization policy to access bucket resources over HTTPS, select HTTPS. If you want the current authorization policy to access bucket resources over HTTP, select HTTP. HTTPS is more secure than HTTP.
To enforce one access method, such as HTTPS, for all requests to resources in the bucket, you must use policy syntax. For more information, see How do I configure HTTPS requests and certificates?.
IP =: Set the IP to be equal to a specific IP address or IP address range. If there are multiple IP addresses, separate them with commas (,).
IP ≠: Set the IP to not be equal to a specific IP address or IP address range. If there are multiple IP addresses, separate them with commas (,).
VPC=: Set to allow access to resources only through a specific VPC or multiple VPCs. You can select a VPC ID created under the current account, or click Enter Other VPC Account to enter a VPC ID created under the current or another account. For more information about how to create a VPC, see Create a VPC and a vSwitch.
VPC ≠: Set to not allow access to resources through a specific VPC. You can select a VPC ID created under the current account, or click Enter Other VPC Account to enter a VPC ID created under the current or another account. For more information about how to create a VPC, see Create a VPC and a vSwitch.
NoteIf a bucket policy includes conditions for both VPC (equal to or not equal to) and IP (equal to or not equal to), the relationship between VPC and IP is `and`. This means the bucket policy must satisfy both the specified VPC and IP conditions.
Click OK.
Method 2: Configure a bucket policy using policy syntax
In the navigation pane on the left, choose Permission Control > Bucket Policy.
On the Bucket Policy page, on the Add Policy By Syntax tab, click Edit.
In the policy editor, enter the bucket policy.
You can edit policy syntax for different scenarios to implement fine-grained permission management. The following examples show bucket policies configured by a resource owner (UID:
174649585760xxxx
) for different authorization scenarios.Example 1: Grant all users permissions to list all files in the `examplebucket` bucket.
{ "Statement": [ { "Action": [ "oss:ListObjects", "oss:ListObjectVersions" ], "Effect": "Allow", "Principal": [ "*" ], "Resource": [ "acs:oss:*:174649585760xxxx:examplebucket" ] } ], "Version": "1" }
Example 2: Deny all users whose source IP addresses are not in the
192.168.0.0/16
range from performing any operations on the `examplebucket` bucket.{ "Version": "1", "Statement": [ { "Effect": "Deny", "Action": "oss:*", "Principal": [ "*" ], "Resource": [ "acs:oss:*:174649585760xxxx:examplebucket" ], "Condition":{ "NotIpAddress": { "acs:SourceIp": ["192.168.0.0/16"] } } } ] }
Example 3: Grant a specified RAM user (UID:
20214760404935xxxx
) read-only permission for thehangzhou/2020
andhangzhou/2015
folders in the target bucket `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 dialog box that appears, click OK.
ossutil
You can use the ossutil command line interface to set a policy for a bucket. For more information about how to install ossutil, see Install ossutil.
The following command sets an access policy for the examplebucket
bucket. This policy denies the user with the ID 1234567890
from performing PutObject
and GetObject
operations on all objects in the bucket.
ossutil api put-bucket-policy --bucket examplebucket --body "{\"Version\":\"1\",\"Statement\":[{\"Action\":[\"oss:PutObject\",\"oss:GetObject\"],\"Effect\":\"Deny\",\"Principal\":[\"1234567890\"],\"Resource\":[\"acs:oss:*:1234567890:*/*\"]}]}"
For more information about this command, see put-bucket-policy.
SDK
The following code examples show how to configure a bucket policy using common SDKs. For code examples of how to configure a bucket policy using other SDKs, see SDK overview.
import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; 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 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. // To release resources, shut down the OSSClient instance when it is no longer needed. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // In the following example, the bucket owner (UID 174649585760xxxx) uses a bucket policy to grant a RAM user (UID 20214760404935xxxx) permissions to and list all objects in examplebucket. 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, "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4, "region"=> "cn-hangzhou" ); $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, authorizationV4: true, // 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.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) # 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 examplebucket. 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"; // 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 parameters as required. 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); 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); }
#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 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"; /* 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); /* 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; }
package main import ( "context" "flag" "log" "strings" "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 the bucket is located. bucketName string // Name of the bucket. ) // Specify the init function 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.") } func main() { // Parse command line parameters. flag.Parse() // 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 region is specified. if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region 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) // Define the bucket policy. policy := `{ "Version": "1", "Statement": [ { "Action": [ "oss:PutObject", "oss:GetObject" ], "Effect": "Deny", "Principal": ["1234567890"], "Resource": ["acs:oss:*:1234567890:*/*"] } ] }` // Create a request to configure a bucket policy. request := &oss.PutBucketPolicyRequest{ Bucket: oss.Ptr(bucketName), // Name of the bucket. Body: strings.NewReader(policy), // The bucket policy. } // Perform the operation to configure the bucket policy. result, err := client.PutBucketPolicy(context.TODO(), request) if err != nil { log.Fatalf("failed to put bucket policy %v", err) } // Display the result. log.Printf("put bucket policy result:%#v\n", result) }
ossbrowser
Use the ossbrowser graphical management tool
API
Call the PutBucketPolicy operation to set an authorization policy for a bucket.
Configure a bucket policy for a vector bucket
Console
On the Vector Buckets page, click the target bucket. In the navigation pane on the left, choose Permission Management > Bucket Policy.
Click Add Policy By Syntax and enter the policy in the policy editor. For example, to grant users read and write permissions on the vector data in
my-vector-bucket
:{ "Version": "1", "Statement": [ { "Effect": "Allow", "Action": [ "oss:PutVectors", "oss:GetVectors" ], "Principal": [ "*" ], "Resource": [ "acs:ossvector:*:*:bucket/my-vector-bucket/*" ] } ] }
Click OK.
ossutil
The following example shows how to set an authorization policy for a vector bucket to allow specified users to perform vector-related operations. The policy is defined in a JSON configuration file named `vector-policy.json`. The content of the file is as follows:
{ "Version":"1", "Statement":[ { "Action":[ "oss:PutVectors", "oss:GetVectors" ], "Effect":"Deny", "Principal":["1234567890"], "Resource":["acs:ossvector:cn-hangzhou:1234567890:*"] } ] }
ossutil vectors-api put-bucket-policy --bucket vector-example --body file://vector-policy.json
Use the JSON configuration file to set the vector bucket policy:
ossutil vectors-api put-bucket-policy --bucket vector-example --body "{\"Version\":\"1\",\"Statement\":[{\"Action\":[\"oss:PutVectors\",\"oss:GetVectors\",\"oss:QueryVectors\"],\"Effect\":\"Allow\",\"Principal\":[\"1234567890\"],\"Resource\":[\"acs:ossvector:cn-hangzhou:1234567890:bucket/vector-example/*\"]}]}"
SDK
Python
import argparse import alibabacloud_oss_v2 as oss import alibabacloud_oss_v2.vectors as oss_vectors parser = argparse.ArgumentParser(description="vector put bucket policy sample") 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('--account_id', help='The account id.', required=True) def main(): args = parser.parse_args() # Loading credentials values from the environment variables credentials_provider = oss.credentials.EnvironmentVariableCredentialsProvider() # Using the SDK's default configuration cfg = oss.config.load_default() cfg.credentials_provider = credentials_provider cfg.region = args.region cfg.account_id = args.account_id if args.endpoint is not None: cfg.endpoint = args.endpoint vector_client = oss_vectors.Client(cfg) policy_content = ''' { "Version":"1", "Statement":[ { "Action":[ "oss:PutVectors", "oss:GetVectors" ], "Effect":"Deny", "Principal":["1234567890"], "Resource":["acs:ossvector:cn-hangzhou:1234567890:*"] } ] } ''' result = vector_client.put_bucket_policy(oss_vectors.models.PutBucketPolicyRequest( bucket=args.bucket, body=policy_content )) print(f'status code: {result.status_code},' f' request id: {result.request_id},' ) if __name__ == "__main__": main()
Go
package main import ( "context" "flag" "log" "strings" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials" "github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/vectors" ) var ( region string bucketName string accountId string ) func init() { flag.StringVar(®ion, "region", "", "The region in which the vector bucket is located.") flag.StringVar(&bucketName, "bucket", "", "The name of the vector bucket.") flag.StringVar(&accountId, "account-id", "", "The ID of the vector account.") } func main() { flag.Parse() if len(bucketName) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, bucket name required") } if len(region) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, region required") } if len(accountId) == 0 { flag.PrintDefaults() log.Fatalf("invalid parameters, accountId required") } cfg := oss.LoadDefaultConfig(). WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()). WithRegion(region).WithAccountId(accountId) client := vectors.NewVectorsClient(cfg) request := &vectors.PutBucketPolicyRequest{ Bucket: oss.Ptr(bucketName), Body: strings.NewReader(`{ "Version":"1", "Statement":[ { "Action":[ "oss:PutVectors", "oss:GetVectors" ], "Effect":"Deny", "Principal":["1234567890"], "Resource":["acs:ossvector:cn-hangzhou:1234567890:*"] } ] }`), } result, err := client.PutBucketPolicy(context.TODO(), request) if err != nil { log.Fatalf("failed to put vector bucket policy %v", err) } log.Printf("put vector bucket policy result:%#v\n", result) }
API
Call the PutBucketPolicy operation to set an authorization policy for a vector bucket.
Access authorized resources
After the bucket policy is configured, you can access the authorized resources in the following ways:
File URL (only when the authorization object is all users)
In a browser, you can use the default domain name or a custom domain name of the bucket and the file path to access the resource. For example,
http://mybucket.oss-cn-beijing.aliyuncs.com/file/myphoto.png
. For more information, see Access OSS over IPv6.Console
Log on to the OSS console. In the navigation pane on the left, click the plus sign (+) next to My Favorite Paths to add the bucket and file path to which you have access. For more information, see Access paths.
ossutil
Use the authorized account to access the authorized resources using ossutil. For more information, see ossutil.
ossbrowser
Log on to ossbrowser using an authorized account. When you log on, enter the file directory to which you have access in the Preset OSS Path field. For more information, see Graphical management tool ossbrowser 1.0.
OSS SDK
Access authorized resources using the Java, PHP, Node.js, Python, Browser.js, .NET, Android, Go, iOS, C++, or C SDK.