Use o SDK (kit de desenvolvimento de software) C++ para configurar regras de acesso no Object Storage Service (OSS) com base no cabeçalho de requisição Referer. Defina uma lista de permissões ou lista de bloqueio de Referer e especifique se requisições com Referer vazio são permitidas. Essas regras bloqueiam Referers específicos e impedem o acesso aos seus arquivos do OSS, evitando que outros sites façam hotlink dos seus arquivos e reduzindo custos desnecessários de tráfego.
Precauções
Antes de configurar a proteção contra hotlink, familiarize-se com esse recurso. Para mais informações, consulte Hotlink protection.
Neste tópico, é usado o endpoint público da região China (Hangzhou). Para acessar o OSS a partir de outros serviços Alibaba Cloud na mesma região, use um endpoint interno. Para mais informações sobre regiões e endpoints do OSS, consulte Regions and endpoints.
Este tópico demonstra como criar uma instância OSSClient com um endpoint do OSS. Para configurações alternativas, como uso de domínio personalizado ou autenticação com credenciais do Security Token Service (STS), consulte Create an OssClient instance.
Para configurar a proteção contra hotlink, você precisa da permissão
oss:PutBucketReferer. Para consultar as configurações de proteção contra hotlink, é necessária a permissãooss:GetBucketReferer. Para mais informações, consulte Grant a custom policy.
Configurar a proteção contra hotlink
O código de exemplo a seguir demonstra como configurar a proteção contra hotlink para um 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;
}
Obter a configuração de proteção contra hotlink
O código de exemplo a seguir ilustra como consultar as configurações de proteção contra hotlink de um 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;
}
Excluir regras de proteção contra hotlink
O código de exemplo a seguir mostra como excluir as configurações de proteção contra hotlink de um 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;
}
Referências
Para obter o código de exemplo completo da proteção contra hotlink, acesse GitHub.
Para mais informações sobre a operação de API para configurar a proteção contra hotlink, consulte PutBucketReferer.
Para detalhes sobre a operação de API para recuperar a configuração de proteção contra hotlink, consulte GetBucketReferer.