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:Jan 31, 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 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.

  • 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.

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 (
    "fmt"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
)

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 {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // 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. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    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.alibabacloud.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{
    []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 {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }

    fmt.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 (
    "fmt"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
)

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 {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // 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. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Query the hotlink protection configurations. 
	refRes, err := client.GetBucketReferer(bucketName)
	if err != nil {
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.Println("Allow Empty Referer: ", refRes.AllowEmptyReferer)
	if refRes.AllowTruncateQueryString != nil {
		fmt.Println("Allow Truncate QueryString: ", *refRes.AllowTruncateQueryString)
	}
	if len(refRes.RefererList) > 0 {
		for _, referer := range refRes.RefererList {
			fmt.Println("Referer List: ", referer)
		}
	}
	if refRes.RefererBlacklist != nil {
		for _, refererBlack := range refRes.RefererBlacklist.Referer {
			fmt.Println("Referer Black List: ", refererBlack)
		}
	}
	fmt.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 (
    "fmt"
    "github.com/aliyun/aliyun-oss-go-sdk/oss"
    "os"
)

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 {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // 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. 
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }
    // Delete the hotlink protection configurations. 
    var delBucketReferer oss.RefererXML
	delBucketReferer.RefererList = []string{}
	delBucketReferer.AllowEmptyReferer = true
	err = client.SetBucketRefererV2(bucketName,delBucketReferer)
	if err!=nil{
		fmt.Println("Error:", err)
		os.Exit(-1)
	}
	fmt.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 PutBucketReferer.

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