Todos os produtos
Search
Central de documentação

Object Storage Service:Bucket policy (Go SDK V1)

Última atualização: Jul 03, 2026

A bucket policy é uma política de autorização para buckets do Object Storage Service (OSS). Use essa política para conceder ou negar acesso granular a recursos específicos do OSS a visitantes autenticados — como contas Alibaba Cloud, usuários do Resource Access Management (RAM) e funções RAM — ou a visitantes anônimos. Por exemplo, você pode conceder permissões de somente leitura em recursos específicos do OSS a um usuário RAM de outra conta Alibaba Cloud.

Observações

  • Antes de configurar uma bucket policy, certifique-se de compreender bem esse recurso. Para mais informações, consulte Bucket policy.

  • Este tópico usa o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços Alibaba Cloud na mesma região, use um endpoint interno. Para obter detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.

  • Neste exemplo, as credenciais de acesso são obtidas de variáveis de ambiente. Para saber como configurar credenciais de acesso, consulte Configurar credenciais de acesso.

  • Este tópico demonstra a criação de uma instância OSSClient com um endpoint do OSS. Para outras configurações, como uso de domínio personalizado ou autenticação via Security Token Service (STS), consulte Configurar um cliente (Go SDK V1).

  • Para definir uma bucket policy, você precisa da permissão oss:PutBucketPolicy. Para obter uma bucket policy, é necessária a permissão oss:GetBucketPolicy. Para excluir uma bucket policy, você deve ter a permissão oss:DeleteBucketPolicy. Para mais detalhes, consulte Conceder uma política personalizada.

Código de exemplo

Defina uma bucket policy

O código a seguir mostra como definir uma bucket policy:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// The following example shows how a resource owner (the bucket owner with UID 174649585760xxxx) uses a bucket policy to grant a specified user (the RAM user with UID 20214760404935xxxx) permissions to list all files in the examplebucket.
	policyConfig := `
    {
        "Statement": [
            {
                "Action": [
                    "oss:GetObject",
                    "oss:ListObjects"
                ],
                "Principal": [
                    "20214760404935xxxx"           
                ],
                "Effect" : "Allow",
                "Resource" : ["acs:oss:*:174649585760xxxx:examplebucket/*"]
            }
        ],
        "Version": "1"
    }`

	// Set the bucket policy.
	bucketName := "examplebucket"
	err = client.SetBucketPolicy(bucketName, policyConfig)
	if err != nil {
		log.Fatalf("Failed to set bucket policy for '%s': %v", bucketName, err)
	}

	log.Println("SetBucketPolicy success")
}

Obter uma bucket policy

O código a seguir mostra como obter uma bucket policy:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Get the bucket policy configuration.
	bucketName := "yourBucketName"
	strPolicy, err := client.GetBucketPolicy(bucketName)
	if err != nil {
		log.Fatalf("Failed to get bucket policy for '%s': %v", bucketName, err)
	}

	log.Printf("Bucket policy for '%s': %s", bucketName, strPolicy)
}

Exclua uma bucket policy

O código a seguir mostra como excluir uma bucket policy:

package main

import (
	"log"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

func main() {
	// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Failed to create credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the Endpoint of the bucket. For example, for a bucket in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, set the Endpoint as needed.
	// Set yourRegion to the region where the bucket is located. For example, for a bucket in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, set the region as needed.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Set the signature version.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Failed to create OSS client: %v", err)
	}

	// Delete the bucket policy.
	bucketName := "yourBucketName"
	err = client.DeleteBucketPolicy(bucketName)
	if err != nil {
		log.Fatalf("Failed to delete bucket policy for '%s': %v", bucketName, err)
	}

	log.Println("DeleteBucketPolicy success")
}

Referências

  • Para mais informações sobre a operação de API que define uma bucket policy, consulte SetBucketPolicy.

  • Para obter detalhes sobre a operação de API que recupera uma bucket policy, consulte GetBucketPolicy.

  • Para saber mais sobre a operação de API que exclui uma bucket policy, consulte DeleteBucketPolicy.