Todos los productos
Search
Centro de documentos

Object Storage Service:Protección contra hotlinking (Go SDK V1)

Última actualización: Sep 03, 2026

Configure reglas de acceso basadas en Referer (lista blanca de Referer, lista negra de Referer y manejo de Referer vacío) mediante el SDK de Go para bloquear solicitudes no autorizadas y prevenir el hotlinking.

Notas de uso

  • Antes de configurar la protección contra hotlinking, familiarícese con esta función. Para obtener más información, consulte Hotlink protection.

  • En este tema se utiliza el endpoint público de la región China (Hangzhou). Si desea acceder a OSS desde otros servicios de Alibaba Cloud en la misma región, utilice un endpoint interno. Para obtener más información sobre las regiones y endpoints de OSS, consulte Regions and endpoints.

  • En este tema, las credenciales de acceso se obtienen de variables de entorno. Para obtener más información sobre cómo configurar las credenciales de acceso, consulte Configure access credentials.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para otras configuraciones, como usar un dominio personalizado o autenticarse con credenciales de Security Token Service (STS), consulte Configure a client (Go SDK V1).

  • Para configurar la protección contra hotlinking, requiere el permiso oss:PutBucketReferer. Para consultar las configuraciones de protección contra hotlinking, requiere el permiso oss:GetBucketReferer. Para obtener más información, consulte Grant a custom policy.

Código de ejemplo

Configurar protección contra hotlinking

El siguiente código configura la protección contra hotlinking para un bucket.

package main

import (
	"log"

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

func main() {
	// Specify the bucket name.
	bucketName := "examplebucket"

	// 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 configured.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	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("Error creating OSS client: %v", err)
	}

	var setBucketReferer oss.RefererXML
	// Add referers to the Referer whitelist and allow requests with an empty Referer header. The Referer parameter supports the asterisk (*) and question mark (?) wildcard characters.
	setBucketReferer.RefererList = []string{
		"http://www.aliyun.com",
		"https://www.aliyun.com",
		"https://www.www.alibabacloud.com/help",
		"http://www.?.aliyuncs.com",
	}
	// Add referers to the Referer blacklist. Go SDK V2.2.8 and later support Referer blacklists.
	setBucketReferer.RefererBlacklist = &oss.RefererBlacklist{
		Referer: []string{
			"http://www.refuse.com",
			"https://*.hack.com",
			"http://ban.*.com",
			"https://www.?.deny.com",
		},
	}
	setBucketReferer.AllowEmptyReferer = true
	boolFalse := false
	setBucketReferer.AllowTruncateQueryString = &boolFalse

	err = client.SetBucketRefererV2(bucketName, setBucketReferer)
	if err != nil {
		log.Fatalf("Error setting bucket referer: %v", err)
	}

	log.Println("Set Bucket Referer Success")
}

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

var (
	region     string
	bucketName string
)

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() {
	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")
	}

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	request := &oss.PutBucketRefererRequest{
		Bucket: oss.Ptr(bucketName),
		RefererConfiguration: &oss.RefererConfiguration{
			AllowEmptyReferer: oss.Ptr(false),
			RefererList: &oss.RefererList{
				Referers: []string{""},
			},
		},
	}
	result, err := client.PutBucketReferer(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to put bucket referer %v", err)
	}

	log.Printf("put bucket referer result:%#v\n", result)
}

Obtener configuración de protección contra hotlinking

El siguiente código recupera la configuración de protección contra hotlinking de un bucket.

package main

import (
	"log"

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

func main() {
	// Specify the bucket name.
	bucketName := "yourBucketName"

	// 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 configured.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	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("Error creating OSS client: %v", err)
	}

	// Get the hotlink protection configurations.
	refRes, err := client.GetBucketReferer(bucketName)
	if err != nil {
		log.Fatalf("Error getting bucket referer: %v", err)
	}

	// Print the hotlink protection configuration information.
	log.Println("Allow Empty Referer:", refRes.AllowEmptyReferer)
	if refRes.AllowTruncateQueryString != nil {
		log.Println("Allow Truncate QueryString:", *refRes.AllowTruncateQueryString)
	}
	if len(refRes.RefererList) > 0 {
		for _, referer := range refRes.RefererList {
			log.Println("Referer List:", referer)
		}
	}
	if refRes.RefererBlacklist != nil && len(refRes.RefererBlacklist.Referer) > 0 {
		for _, refererBlack := range refRes.RefererBlacklist.Referer {
			log.Println("Referer Black List:", refererBlack)
		}
	}

	log.Println("Get Bucket Referer Success")
}

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

var (
	region     string
	bucketName string
)

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() {
	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")
	}

	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region)

	client := oss.NewClient(cfg)

	request := &oss.GetBucketRefererRequest{
		Bucket: oss.Ptr(bucketName),
	}
	result, err := client.GetBucketReferer(context.TODO(), request)
	if err != nil {
		log.Fatalf("failed to get bucket referer %v", err)
	}

	log.Printf("get bucket referer result:%#v\n", result)
}

Eliminar configuración de protección contra hotlinking

El siguiente código elimina la configuración de protección contra hotlinking de un bucket.

package main

import (
	"log"

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

func main() {
	// Set yourBucketName to the bucket name.
	bucketName := "yourBucketName"

	// 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 configured.
	provider, err := oss.NewEnvironmentVariableCredentialsProvider()
	if err != nil {
		log.Fatalf("Error creating credentials provider: %v", err)
	}

	// Create an OSSClient instance.
	// Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. For other regions, use the actual endpoint.
	// Set yourRegion to the region of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the region to cn-hangzhou. For other regions, use the actual region.
	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("Error creating OSS client: %v", err)
	}

	// Clear the hotlink protection configurations.
	var delBucketReferer oss.RefererXML
	delBucketReferer.RefererList = []string{}
	delBucketReferer.AllowEmptyReferer = true

	err = client.SetBucketRefererV2(bucketName, delBucketReferer)
	if err != nil {
		log.Fatalf("Error clearing bucket referer: %v", err)
	}

	log.Println("Delete Bucket Referer Success")
}

Referencias

  • Código de ejemplo completo de protección contra hotlinking: GitHub.

  • API para configurar la protección contra hotlinking: SetBucketRefererV2.

  • API para consultar la protección contra hotlinking: GetBucketReferer.