防盗链

更新时间: 2020-03-24

目录

设置防盗链

获取防盗链信息

删除防盗链

本节主要介绍桶的防盗链管理。

为了防止您在OSS上的数据被其他人盗链而产生额外费用,您可以设置防盗链功能,包括以下参数:

  • Referer白名单。仅允许指定的域名访问OSS资源。
  • 是否允许空Referer。如果不允许空Referer,则只有HTTP或HTTPS header中包含Referer字段的请求才能访问OSS资源;不允许为空的桶下的文件不能进行header头设置。

设置防盗链

以下代码用于设置防盗链:

// Endpoint以华北三为例,其它Region请按实际情况填写。
String endpoint = "oss.cn-north-3.inspurcloudoss.com";
String accessKey = "<yourAccessKey>";
String secretKey = "<yourSecretKey>";
String bucketName = "<yourBucketName>";
String userId = "<yourUserId>";

//创建OSSClient实例
OSSClientImpl ossClient = new OSSClientImpl(endpoint, accessKey, secretKey);

//设置防盗链
List<Condition> conditions = new ArrayList<>();

List<String> referers = new ArrayList<>();
// 添加Referer白名单。Referer参数支持通配符星号(*)和问号(?)
referers.add("http://www.test.com");
referers.add("http://www.*.com");
referers.add("http://www.?.com");

conditions.add(new Condition().withConditionKey("aws:Referer").withType("StringNotLike").withValues("http://asdas.asdass"));
Condition condition = new Condition();
condition.setConditionKey("aws:Referer");
//type支持"StringNotLikeIfExists"、"StringNotLike"
condition.setType("StringNotLike");
condition.setValues(referers);

//Deny表示拒绝除了设置的域名外的访问者访问,一般设置为Deny
Statement statement = new Statement(Statement.Effect.Deny);
statement.setConditions(conditions);
statement.setId("Anti stealing link of user:" + userId);
statement.withActions(OSSActions.GetObject);
statement.withPrincipals(Principal.All);
statement.withResources(new Resource("arn:aws:s3:::" + bucketName + "/*"));
Collection<Statement> statements = new ArrayList<>();
statements.add(statement);
Policy policy = new Policy();
policy.setStatements(statements);
policy.setId("<policyId>");
ossClient.setBucketPolicy(bucketName, policy.toJson());

获取防盗链信息

以下代码用于获取防盗链信息:

// Endpoint以华北三为例,其它Region请按实际情况填写。
String endpoint = "oss.cn-north-3.inspurcloudoss.com";
String accessKey = "<yourAccessKey>";
String secretKey = "<yourSecretKey>";
String bucketName = "<yourBucketName>";

//创建OSSClient实例
OSSClientImpl ossClient = new OSSClientImpl(endpoint, accessKey, secretKey);

//获取防盗链信息
BucketPolicy bucketPolicy = ossClient.getBucketPolicy(bucketName);
System.out.println("Getting bucket policy: " + bucketPolicy.getPolicyText());

删除防盗链

以下代码用于删除防盗链:

// Endpoint以华北三为例,其它Region请按实际情况填写。
String endpoint = "oss.cn-north-3.inspurcloudoss.com";
String accessKey = "<yourAccessKey>";
String secretKey = "<yourSecretKey>";
String bucketName = "<yourBucketName>";

//创建OSSClient实例
OSSClientImpl ossClient = new OSSClientImpl(endpoint, accessKey, secretKey);

//删除防盗链
ossClient.deleteBucketPolicy(bucketName);