Todos los productos
Search
Centro de documentos

Object Storage Service:Hotlink protection (C++ SDK)

Última actualización: Sep 22, 2026

Con el kit de desarrollo de software (SDK) de C++, usted puede configurar reglas de acceso en Object Storage Service (OSS) basadas en el encabezado de solicitud Referer. Es posible establecer una lista blanca o negra de Referer y especificar si se permiten las solicitudes con un Referer vacío. Estas reglas bloquean el acceso a sus archivos de OSS desde los Referer indicados. De esta manera, se evita que otros sitios web utilicen sus archivos mediante hotlinking y se reducen los costos de tráfico innecesarios.

Precauciones

  • Antes de configurar la protección contra hotlinking, asegúrese de conocer bien 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 ubicados en la misma región que OSS, utilice un endpoint interno. Para obtener más información sobre las regiones y los endpoints de OSS, consulte Regions and endpoints.

  • Este tema muestra cómo crear una instancia de OSSClient con un endpoint de OSS. Para conocer configuraciones alternativas, como el uso de un dominio personalizado o la autenticación con credenciales de Security Token Service (STS), consulte Create an OssClient instance.

  • Para configurar la protección contra hotlinking, necesita 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.

Configurar la protección contra hotlinking

A continuación se muestra un ejemplo de código para configurar la protección contra hotlinking en un bucket:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
    
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Set the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Set hotlink protection. */
    SetBucketRefererRequest request(BucketName);
    request.addReferer("http://www.aliyun.com");
    request.addReferer("https://www.aliyun.com");
    /* request.addReferer("https://www.alibabacloud.com/help");*/
    /* request.addReferer("http://www.?.aliyuncs.com");*/
    request.setAllowEmptyReferer(true);

    auto outcome = client.SetBucketReferer(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "SetBucketReferer fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Obtener la configuración de protección contra hotlinking

A continuación se muestra un ejemplo de código para consultar la configuración de protección contra hotlinking de un bucket:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Set the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Get hotlink protection information. */
    GetBucketRefererRequest request(BucketName);
    auto outcome = client.GetBucketReferer(request);

    if (outcome.isSuccess()) {
        std::cout << " GetBucketReferer success, AllowEmptyReferer: " << outcome.result().AllowEmptyReferer() <<
        " ,Referer size: " << outcome.result().RefererList().size() << std::endl;
    }
    else { 
        /* Handle exceptions. */
        std::cout << "GetBucketReferer fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Eliminar las reglas de protección contra hotlinking

A continuación se muestra un ejemplo de código para eliminar la configuración de protección contra hotlinking de un bucket:

#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
            
    /* Set yourEndpoint to the Endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Set yourRegion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the Region to cn-hangzhou. */
    std::string Region = "yourRegion";
    /* Set the bucket name, for example, examplebucket. */
    std::string BucketName = "examplebucket";

    /* Initialize network resources. */
    InitializeSdk();

    ClientConfiguration conf;
    conf.signatureVersion = SignatureVersionType::V4;
    /* Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);
    client.SetRegion(Region);

    /* Delete hotlink protection rules. You cannot directly delete the rules. Instead, create a new rule that allows empty Referers to overwrite the previous rules. */
    SetBucketRefererRequest request(BucketName);
    request.setAllowEmptyReferer(true);

    auto outcome = client.SetBucketReferer(request);

    if (!outcome.isSuccess()) {
        /* Handle exceptions. */
        std::cout << "CleanBucketReferer fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
        return -1;
    }

    /* Release network resources. */
    ShutdownSdk();
    return 0;
}

Referencias

  • Para consultar el código de ejemplo completo sobre la protección contra hotlinking, visite GitHub.

  • Para obtener más información sobre la operación de API que configura la protección contra hotlinking, consulte PutBucketReferer.

  • Para obtener más información sobre la operación de API que recupera la configuración de protección contra hotlinking, consulte GetBucketReferer.