All Products
Search
Document Center

Object Storage Service:Grant access to OSS by using a bucket policy

Last Updated:Nov 14, 2025

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 under your Alibaba Cloud account or other Alibaba Cloud accounts access to specified resources in a bucket. In addition to using policy syntax, you can use the graphical user interface (GUI) to quickly grant permissions based on your business scenarios.

Precautions

  • By default, an Alibaba Cloud account has the permission to configure bucket policies. If you want to use a RAM user or Security Token Service (STS) to configure a bucket policy, you must have the oss:PutBucketPolicy permission. For more information, see Grant custom permissions 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 policies.

  • When you configure a bucket policy, if you grant permissions to all accounts (*), which includes anonymous requests, and do not include a Condition element, the bucket policy applies to all users except the bucket owner. If you grant permissions to all accounts (*) and include a Condition element, the bucket policy applies to all users, including the bucket owner.

    Important

    Setting the Principal field to an empty list (example: Principal:[]) is equivalent to specifying a wildcard principal (Principal: ["*"]). This grants universal access to the resource, including to anonymous users. An empty Principal list must not be interpreted as a mechanism to deny all access. This misinterpretation can result in unintended public exposure. To properly restrict access, you must explicitly specify the intended principals or use a policy statement with an Effect of Deny.

  • 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 access to manage an entire bucket or specific resources within a bucket.

  • Granting different permissions, such as read-only, read/write, or full control, to different RAM users under the same account to access or manage bucket resources.

Configure an authorization policy

Configure a bucket policy

Console

Method 1: Configure a bucket policy using the GUI

  1. In the left-side navigation pane, click Buckets. On the Buckets page, find and click the desired bucket.

  2. In the navigation pane on the left, choose Permission Control > Bucket Policy.

  3. On the Bucket Policy page, click the Add in GUI tab and then click Authorize.

  4. In the Authorize panel, configure the parameters as described in the following table and then click OK.

    Parameter

    Description

    Applied To

    Grant other users access to the entire bucket or specific resources within the bucket.

    • Whole Bucket: The policy applies to the entire bucket.

    • Specific Resources: The policy applies only to the specified resources. You can configure multiple policies for specified resources.

      • Grant permissions at the folder level

        To grant access to all subdirectories and files in a folder, append a wildcard character (*) to the folder name. For example, to grant access to all subdirectories and files in the abc folder, enter abc/*.

      • Grant permissions to a specific file

        To grant access to a specific file in a folder, enter the full path of the file without 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 the account type.

    • All Accounts (*): Select this option to grant all users access to the specified resources.

    • RAM User: Select this option to grant a RAM user 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, enter a keyword of the RAM user name in the search box for a fuzzy match.

      Important

      Your account must be an Alibaba Cloud account or a RAM user that has management permissions on the 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 Account: Select this option to grant access permissions to other Alibaba Cloud accounts, RAM users, and 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, use the format arn:sts::{RoleOwnerUid}:assumed-role/{RoleName}/{RoleSessionName}. For example, if the RAM role is testrole, the UID of the role owner is 137918634953xxxx, and the role session name is testsession, enter arn:sts::137918634953xxxx:assumed-role/testrole/testsession. To grant permissions to all RAM roles, use the wildcard character (*). For example, enter arn:sts::*:*/*/*. For more information, see AssumeRole - Obtain temporary identity credentials of a RAM role.

      Important

      When 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 an OSS API. For example, to access authorized resources using ossutil, configure access credentials by following the instructions in Access resources using a temporary token. Then, request the OSS resources to verify that the bucket policy is effective.

    Authorized Operation

    You can grant permissions using Basic Settings or Advanced Settings.

    • Basic Settings

      Select this option and configure the access permissions based on your scenario. Hover the mouse over the mark icon next to each permission to view the list of corresponding actions.

      • Read-Only (excluding ListObject): Grants permissions to view and download the related resources.

      • Read-Only (including ListObject): Grants permissions to view, list, and download the related resources.

      • Read/Write: Grants read and write permissions on the related resources.

      • Full Access: Grants all permissions on the related resources, including read, write, and delete permissions.

      • Deny Access: Denies all operations on the related resources.

      Important
      • To ensure that users of the OSS-HDFS service can access the .dlsdata/ folder and its objects, do not set Actions to Deny Access when you configure a bucket policy for a bucket with OSS-HDFS enabled.

      • If you configure multiple bucket policy rules for a user, the user's permissions are the sum of all policy rules. If any of these bucket policies include a deny permission, the deny permission takes precedence. For example, if you first grant a user read-only permissions and then grant read/write permissions, the user's final permissions are read/write. If you then grant deny access permissions, the user's final permission is deny access.

      • The authorization effect for Read-Only, Read/Write, and Full Control is Allow. The authorization effect for Deny Access is Deny.

    • Advanced Settings

      Select this option and complete the following configurations.

      • Effect: The authorization effect. Valid values: Allow and Deny.

      • Actions: All actions supported by OSS. For more information about action classifications, see RAM policies.

    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 are supported. If you want the current policy to allow access to bucket resources only over HTTPS, select HTTPS. If you want the current policy to allow access to bucket resources only over HTTP, select HTTP. HTTPS provides higher security than HTTP.

      To enforce a specific 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 =: Sets the IP address to be equal to a specific IP address or CIDR block. If there are multiple IP addresses, separate them with commas (,).

    • IP ≠: Sets the IP address to be not equal to a specific IP address or CIDR block. If there are multiple IP addresses, separate them with commas (,).

    • VPC=: Allows access to resources only from a specific VPC or multiple VPCs. You can select the VPC ID of a VPC created under the current account, or click Enter Other VPC Account to enter the VPC ID of a VPC created under the current account or another account. For more information about how to create a VPC, see Create a VPC and a vSwitch.

    • VPC ≠: Denies access to resources from a specific VPC. You can select the VPC ID of a VPC created under the current account, or click Enter Other VPC Account to enter the VPC ID of a VPC created under the current account or another account. For more information about how to create a VPC, see Create a VPC and a vSwitch.

    Note

    If you specify both VPC (equal to or not equal to) and IP (equal to or not equal to) conditions in a bucket policy, the conditions are combined with an AND logic. This means the request must satisfy both the VPC and IP conditions.

  5. Click OK.

Method 2: Configure a bucket policy using policy syntax

  1. In the navigation pane on the left, choose Permission Control > Bucket Policy.

  2. On the Bucket Policy page, click the Add By Syntax tab and then click Edit.

  3. In the policy editor, enter the bucket policy.

    You can write different policy syntaxes for different scenarios to implement fine-grained permission management. The following examples show bucket policies that are configured by a resource owner (UID: 174649585760xxxx) for different authorization scenarios.

    • Example 1: Grant all users the permission to list all files in the examplebucket bucket. The Sid (Statement ID) in the following example provides a readable unique identifier for the statement in the policy. It is used for differentiation, management, and auditing, and does not affect the permission itself.

      {
          "Statement": [
              {
                  "Sid": "AllowListObjects",
                  "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 permissions on the hangzhou/2020 and hangzhou/2015 directories in the examplebucket bucket.

      {
          "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"
      }
  4. Click Save. In the dialog box that appears, click OK.

ossutil

You can use ossutil, a command-line tool, to set a policy for a bucket. To install ossutil, see Install ossutil.

The following command sets an access policy for the examplebucket bucket. The policy denies the user with the ID 1234567890 permission to perform 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 provides examples of how to configure a bucket policy using common software development kits (SDKs). For information about how to configure a bucket policy using other SDKs, see Introduction to OSS SDKs.

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(&region, "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 GUI tool

ossbrowser supports bucket-level operations that are similar to those in the OSS console. You can follow the instructions in the ossbrowser interface to modify the bucket policy. For more information about how to use ossbrowser, see Common operations.

API

Call the PutBucketPolicy operation to set an authorization policy for a bucket.

Access authorized resources

After you configure the bucket policy, you can access the authorized resources in the following ways:

  • File URL (only if the authorized principal is all users)

    In a browser, 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 Use an endpoint that supports IPv6 to access OSS.

  • 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 that you are authorized to access. For more information, see Access paths.

  • ossutil command line interface

    You can use the authorized account to access the authorized resources through ossutil. For more information, see ossutil.

  • ossbrowser GUI tool

    Log on to ossbrowser with the authorized account. In the Preset OSS Path field, enter the file directory that you are authorized to access. For more information, see Graphical management tool ossbrowser 1.0.

  • OSS SDKs

    You can access authorized resources using the Java, PHP, Node.js, Python, Browser.js, .NET, Android, Go, iOS, C++, and C SDKs.

References