本文介绍如何使用防盗链。
为了防止您在OSS上的数据被其他人盗链而产生额外费用,您可以设置防盗链功能,包括以下参数:
- Referer白名单。仅允许指定的域名访问OSS资源。
- 是否允许空Referer。如果不允许空Referer,则只有HTTP或HTTPS header中包含Referer字段的请求才能访问OSS资源。
更多关于防盗链的介绍,请参见开发指南中的设置防盗链。
设置防盗链完整代码请参见GitHub。
设置防盗链
以下代码用于设置防盗链:
using Aliyun.OSS; using Aliyun.OSS.Common; var endpoint = "<yourEndpoint>"; var accessKeyId = "<yourAccessKeyId>"; var accessKeySecret = "<yourAccessKeySecret>"; var bucketName = "<yourBucketName>"; // 创建OSSClient实例。 var client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { var refererList = new List<string>(); // 添加Referer白名单。Referer参数支持通配符星号(*)和问号(?)。 refererList.Add(" http://www.aliyun.com"); refererList.Add(" http://www.*.com"); refererList.Add(" http://www.?.aliyuncs.com"); var srq = new SetBucketRefererRequest(bucketName, refererList); // 设置防盗链。 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); }
获取防盗链信息
获取防盗链信息完整代码请参见GitHub。
以下代码用于获取防盗链信息:
using Aliyun.OSS; using Aliyun.OSS.Common; var endpoint = "<yourEndpoint>"; var accessKeyId = "<yourAccessKeyId>"; var accessKeySecret = "<yourAccessKeySecret>"; var bucketName = "<yourBucketName>"; // 创建OSSClient实例。 var client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { // 获取防盗链信息。 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)); }
清空防盗链
以下代码用于清空防盗链:
using Aliyun.OSS; using Aliyun.OSS.Common; var endpoint = "<yourEndpoint>"; var accessKeyId = "<yourAccessKeyId>"; var accessKeySecret = "<yourAccessKeySecret>"; var bucketName = "<yourBucketName>"; // 创建OSSClient实例。 var client = new OssClient(endpoint, accessKeyId, accessKeySecret); try { // 防盗链不能直接清空,需要新建一个允许空Referer的规则来覆盖之前的规则。 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); }