All Products
Search
Document Center

Object Storage Service:Configure bucket policies by using OSS SDK for Go

Last Updated:Jan 09, 2025

A bucket policy allows you to allow or deny access of anonymous users or identified users, such as Alibaba Cloud accounts, RAM users, and RAM roles, to specific Object Storage Service (OSS) resources. For example, you can grant read-only permissions on specific OSS resources to a RAM user of another Alibaba Cloud account.

Notes

  • Before you configure bucket policies, make sure that you are familiar with this feature. For more information, see Bucket Policy.

  • The sample code in this topic uses the region ID cn-hangzhou of the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about the regions and endpoints supported by Object Storage Service (OSS), see OSS regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • The oss:PutBucketPolicy permission is required to configure a bucket policy. The oss:GetBucketPolicy permission is required to query a bucket policy. The oss:DeleteBucketPolicy permission is required to delete a bucket policy. For more information, see Authorize custom policies for RAM users.

Sample code

Configure a bucket policy

The following code demonstrates how to configure a bucket policy.

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)
}

Query a bucket policy

The following code demonstrates how to query a bucket policy.

package main

import (
	"context"
	"flag"
	"log"

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

// Define global variables.
var (
	region     string // Region in which 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)

	// Create a request to query the bucket policy.
	request := &oss.GetBucketPolicyRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Make the query request.
	result, err := client.GetBucketPolicy(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket policy %v", err)
	}

	// Display the result.
	log.Printf("get bucket policy result:%#v\n", result)
}

Delete a bucket policy

The following code demonstrates how to delete a bucket policy.

package main

import (
	"context"
	"flag"
	"log"

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

// Define global variables.
var (
	region     string // Region in which 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)

	// Create a request to delete the bucket policy.
	request := &oss.DeleteBucketPolicyRequest{
		Bucket: oss.Ptr(bucketName),
	}

	// Delete the bucket policy.
	result, err := client.DeleteBucketPolicy(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to delete bucket policy %v", err)
	}

	// Display the result.
	log.Printf("delete bucket policy result:%#v\n", result)
}

References

  • For the complete sample code that is used to configure a bucket policy, visit GitHub example.

  • For more information about the API operation that you can call to configure a bucket policy, see PutBucketPolicy.

  • For the complete sample code that is used to query a bucket policy, visit GitHub example.

  • For more information about the API operation that you can call to query a bucket policy, see GetBucketPolicy.

  • For the complete sample code that is used to delete a bucket policy, visit GitHub example.

  • For more information about the API operation that you can call to delete a bucket policy, see DeleteBucketPolicy.