Uma política de bucket é uma política de autorização para buckets do Object Storage Service (OSS). Use uma política de bucket para conceder ou negar acesso granular a recursos específicos do OSS a visitantes autenticados, como contas da Alibaba Cloud, usuários do Resource Access Management (RAM) e funções do 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 do RAM pertencente a outra conta da Alibaba Cloud.
Observações
Antes de configurar uma política de bucket, certifique-se de compreender este recurso. Para mais informações, consulte Bucket policy.
Este tópico utiliza o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre as regiões e endpoints do OSS, consulte Regions and endpoints.
Os exemplos deste tópico obtêm as credenciais de acesso a partir de variáveis de ambiente. Para mais informações sobre como configurar credenciais de acesso, consulte Configure access credentials.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como usar um domínio personalizado ou autenticar com credenciais do Security Token Service (STS), consulte Configure a client (Go SDK V1).
Definir uma política de bucket requer a permissão
oss:PutBucketPolicy, enquanto obtê-la exige a permissãooss:GetBucketPolicy. Por fim, para excluir a política, você precisa da permissãooss:DeleteBucketPolicy. Para mais informações, consulte Grant a custom policy.
Exemplos de código
Definir uma política de bucket
O código a seguir mostra como definir uma política de bucket:
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 política de bucket
Use o código abaixo para obter uma política de bucket:
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)
}
Excluir uma política de bucket
O exemplo a seguir demonstra como excluir uma política de bucket:
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 para definir uma política de bucket, consulte SetBucketPolicy.
Para obter detalhes sobre a operação de API para obter uma política de bucket, consulte GetBucketPolicy.
Para saber mais sobre a operação de API para excluir uma política de bucket, consulte DeleteBucketPolicy.