Configure uma lista de permissões ou uma lista de bloqueios de Referer e defina se deseja permitir requisições com Referer vazio para um bucket do Object Storage Service (OSS). Essa configuração evita acessos não autorizados aos recursos do bucket e previne custos inesperados de tráfego.
Observações de uso
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 obter mais detalhes sobre regiões e endpoints do OSS, consulte Regiões e endpoints.
O exemplo abaixo demonstra 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 Inicialização (C# SDK V1).
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.
Configurar a proteção contra hotlink para um bucket
O código de exemplo a seguir mostra como configurar a proteção contra hotlink em um bucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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.
var endpoint = "yourEndpoint";
// 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket.
var bucketName = "examplebucket";
// 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.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
var refererList = new List<string>();
// Add a Referer whitelist. You can use asterisks (*) and question marks (?) as wildcard characters in Referers.
refererList.Add("http://www.aliyun.com");
refererList.Add("https://www.aliyun.com");
// refererList.Add("http://www.help.alibabacloud.com");
// refererList.Add("http://www.?.aliyuncs.com");
var srq = new SetBucketRefererRequest(bucketName, refererList);
// Configure hotlink protection.
client.SetBucketReferer(srq);
Console.WriteLine("Set bucket:{0} Referer succeeded ", bucketName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
Consultar configurações de proteção contra hotlink
O código de exemplo a seguir mostra como consultar as configurações de proteção contra hotlink de um bucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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.
var endpoint = "yourEndpoint";
// 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket.
var bucketName = "examplebucket";
// 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.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// Query the hotlink protection configurations of the bucket.
var rc = client.GetBucketReferer(bucketName);
Console.WriteLine("Get bucket:{0} Referer succeeded ", bucketName);
Console.WriteLine("allow?" + (rc.AllowEmptyReferer ? "yes" : "no"));
if (rc.RefererList.Referers != null)
{
for (var i = 0; i < rc.RefererList.Referers.Length; i++)
Console.WriteLine(rc.RefererList.Referers[i]);
}
else
{
Console.WriteLine("Empty Referer List");
}
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
finally
{
client.SetBucketReferer(new SetBucketRefererRequest(bucketName));
}
Limpar as configurações de proteção contra hotlink de um bucket
O código de exemplo a seguir mostra como excluir as configurações de proteção contra hotlink de um bucket:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// 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.
var endpoint = "yourEndpoint";
// 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.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket.
var bucketName = "examplebucket";
// 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.
const string region = "cn-hangzhou";
// Create a ClientConfiguration instance and modify the default parameters based on your requirements.
var conf = new ClientConfiguration();
// Use the signature algorithm V4.
conf.SignatureVersion = SignatureVersion.V4;
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
// The hotlink protection configurations of a bucket cannot be directly cleared. To overwrite the existing hotlink protection configurations, you must configure a new hotlink protection rule that allows requests with an empty Referer header.
var srq = new SetBucketRefererRequest(bucketName);
client.SetBucketReferer(srq);
Console.WriteLine("Set bucket:{0} Referer succeeded ", bucketName);
}
catch (OssException ex)
{
Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
Console.WriteLine("Failed with error info: {0}", ex.Message);
}
Referências
Para visualizar o código de exemplo completo sobre proteção contra hotlink, acesse o GitHub.
Para obter detalhes sobre a operação de API usada na configuração da proteção contra hotlink de um bucket, consulte PutBucketReferer.
Para mais informações sobre a operação de API destinada à consulta das configurações de proteção contra hotlink, consulte GetBucketReferer.