`

【FastDFS】FastDFS防盗链

 
阅读更多

一、前言

       我们通过HTTP的方式完成文件的下载。形如

http://172.31.20.220/group1/M00/00/00/rB8UEVrjR1mAV_XWAUWlTgbnZcg938.pdf,但是这样是不安全的,因为只要知道ip和文件路径,就能下载所需文件。因此采用Token方式防盗链

       FastDFS内置防盗链采用Token的方式。Token是带时效的,也就是说在设定的时间范围内,比如1分钟,token是有效的。token包含了文件id、时间戳ts和密钥。FastDFS在URL中带上当前时间戳和带时效的token,参数名分别为ts和token。Token的生成和校验都是在服务端,因此不会存在安全问题。形如

http://172.31.20.220/group1/M00/00/00/rB8UEVrki1uAWDrRAASH9xd2VVI137.pdf?token=

09267ad7bbe6615a79f046ce10eed623&ts=1524898341

 

 

二、配置文件说明

http.conf中防盗链相关的几个参数如下:

http.anti_steal.check_token:是否做token检查,缺省值为false。

http.anti_steal.token_ttl:token TTL,即生成token的有效时长

http.anti_steal.secret_key:生成token的密钥,尽量设置得长一些,千万不要泄露出去

http.anti_steal.token_check_fail:token检查失败,返回的文件内容,需指定本地文件名

配置示例:

# HTTP default content type
http.default_content_type = application/octet-stream

# MIME types mapping filename
# MIME types file format: MIME_type  extensions
# such as:  image/jpeg	jpeg jpg jpe
# you can use apache's MIME file: mime.types
http.mime_types_filename=mime.types

# if use token to anti-steal
# default value is false (0)

#开启token校验
http.anti_steal.check_token=true

# token TTL (time to live), seconds
# default value is 600
http.anti_steal.token_ttl=60

# secret key to generate anti-steal token
# this parameter must be set when http.anti_steal.check_token set to true
# the length of the secret key should not exceed 128 bytes
http.anti_steal.secret_key=FastDFS1234567890

# return the content of the file when check token fail
# default value is empty (no file sepecified)
http.anti_steal.token_check_fail=/etc/fdfs/anti-steal.jpg

比如http.anti_steal.token_ttl=60,也就是说token的失效时间为60秒。当超过60秒时,token失效。此时再拿原来的URL去访问图片资源。将会失效,从而显示anti-steal.jpg图片。

java client代码如下:

//fid为从数据库中读出的值
String fid="group2/M00/00/02/wKjgzFrpTGOAUl37AABFbiLVDsI531.png";
String substring = fid.substring(fid.indexOf("/")+1);
//unix时间戳 以秒为单位
int ts = (int) (System.currentTimeMillis() / 1000);
String secret_key = "FastDFS1234567890";
String token=new String();
try {
	token= ProtoCommon.getToken(substring, ts, secret_key);
} catch (UnsupportedEncodingException e) {
	e.printStackTrace();
}
 
 StringBuilder sb = new StringBuilder();
 sb.append("192.168.224.208/")
 sb.append(fid);
 sb.append("token=").append(token);
 sb.append("&ts=").append(ts);
 return sb.toString();

 

四、生成的token验证无法通过

出现这样的问题请进行如下两项检查:

1、  确认调用token生成函数,传递的文件id中没有包含group name,传递的文件id形如:

M00/00/00/rB8UEVrjR1mAV_XWAUWlTgbnZcg938.pdf

2、  确认服务器时间基本是一致的,注意服务器时间不能相差太多,不要相差到分钟级别。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics