All Products
Search
Document Center

Object Storage Service:Use the SDK for Go to configure Referer-based hotlink protection to prevent unauthorized reference to OSS objects

Last Updated:Nov 05, 2024

You can configure a Referer whitelist or a Referer blacklist and specify whether to allow a request with an empty Referer for an Object Storage Service (OSS) bucket to prevent unauthorized access to resources in the bucket and unexpected traffic fees.

Usage notes

  • Before you configure hotlink protection, make sure that you familiarize yourself with this feature. For more information, see Hotlink protection.

  • In this topic, the public endpoint of the China (Hangzhou) region is used. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use an internal endpoint. For more information about OSS regions and endpoints, see Regions, endpoints and open ports.

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

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Initialization.

  • To configure hotlink protection, you must have the oss:PutBucketReferer permission. To query hotlink protection configurations, you must have the oss:GetBucketReferer permission. For more information, see Attach a custom policy to a RAM user.

Sample code

Configure a Referer whitelist for a bucket

The following code provides an example on how to configure hotlink protection for a bucket:

package main

import (
	"log"

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

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

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

	// Create an OSSClient instance. 
        // 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. Specify your actual endpoint. 
	// 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. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	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 specify that an empty Referer field is not allowed. You can use an asterisk (*) or a question mark (?) as a wildcard to set the Referer parameter. 
	setBucketReferer.RefererList = []string{
		"http://www.aliyun.com",
		"https://www.aliyun.com",
		"https://www.help.aliyun.com",
		"http://www.?.aliyuncs.com",
	}
	// Add a Referer blacklist. OSS SDK for Go V2.2.8 or later supports Referer blacklist settings. 
	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")
}

Query the hotlink protection configurations of a bucket

The following code provides an example on how to query the hotlink protection configurations of a bucket:

package main

import (
	"log"

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

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

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

	// Create an OSSClient instance. 
        // 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. Specify your actual endpoint. 
	// 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. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

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

	// Display the hotlink protection configurations. 
	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")
}

Delete the hotlink protection configurations of a bucket

The following code provides an example on how to delete the hotlink protection configurations of a bucket:

package main

import (
	"log"

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

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

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

	// Create an OSSClient instance. 
        // 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. Specify your actual endpoint. 
	// 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. Specify the actual region.
	clientOptions := []oss.ClientOption{oss.SetCredentialsProvider(&provider)}
	clientOptions = append(clientOptions, oss.Region("yourRegion"))
	// Specify the version of the signature algorithm.
	clientOptions = append(clientOptions, oss.AuthVersion(oss.AuthV4))
	client, err := oss.New("yourEndpoint", "", "", clientOptions...)
	if err != nil {
		log.Fatalf("Error creating OSS client: %v", err)
	}

	// Delete 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")
}

References

  • For the complete sample code of hotlink protection, visit GitHub.

  • For more information about the API operation that you can call to configure hotlink protection for a bucket, see SetBucketRefererV2.

  • For more information about the API operation that you can call to query the hotlink protection configurations of a bucket, see GetBucketReferer.