Use o kit de desenvolvimento de software (SDK) 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 de bloqueios de Referer e especifique se requisições com Referer vazio são permitidas. Essas regras impedem que Referers específicos acessem seus arquivos no 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 Proteção contra hotlink.
Este tópico utiliza o endpoint público da região China (Hangzhou). Caso precise acessar o OSS a partir de outros serviços da Alibaba Cloud na mesma região, utilize um endpoint interno. Para mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
Os exemplos abaixo demonstram a criação de 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 Criar uma instância OssClient.
Para configurar a proteção contra hotlink, é necessária a permissão
oss:PutBucketReferer. Para consultar as configurações existentes, é necessária a permissãooss:GetBucketReferer. Para mais informações, consulte Conceder uma política personalizada.
Definir proteção contra hotlink
O código de exemplo a seguir mostra 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 mostra como consultar as configurações de 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 visualizar o código de exemplo completo sobre proteção contra hotlink, acesse o GitHub.
Para obter mais detalhes sobre a operação de API usada para definir a proteção contra hotlink, consulte PutBucketReferer.
Para saber mais sobre a operação de API que recupera a configuração de proteção contra hotlink, consulte GetBucketReferer.