1、背景

咱们能够通过fastdfs实现一个分布式文件系统,如果咱们的fastdfs部署在外网,那么任何一个人晓得了咱们的上传接口,那么它就能够文件的上传和拜访。那么咱们如何阻止别人拜访咱们fastdfs服务器上的文件呢?此处就须要应用fastdfs的防盗链性能。

2、实现原理

fastdfs的防盗链是通过token机制来实现的。当咱们开启防盗链性能后,须要在url后减少2个额定的参数tokentstokents的生成都是须要在服务端。

2.1 开启防盗链

vim /etc/fdfs/http.conf

# true 示意开启防盗链http.anti_steal.check_token = true# token的过期工夫,单位为秒http.anti_steal.token_ttl = 60# 密钥,不可透露,用于生成tokenhttp.anti_steal.secret_key = thisisasecuritykey# 当图片回绝拜访后,显示的图片,此图片须要可拜访,不然可能会呈现问题http.anti_steal.token_check_fail = /data/fastdfs/401.jpg

http.anti_steal.token_check_fail 指定的图片须要可拜访,否则可能会呈现问题

2.2 重启 nginx

/usr/local/nginx/sbin/nginx -s reload

2.3 Java代码生成token

1、token生成规定

token = md5(文件ID+私钥+工夫戳)

文件ID:不能蕴含group

group1/M00/00/00/wKh5iWNBl7-AKvj1AAAwWD4VeAg577.jpg`须要替换成`M00/00/00/wKh5iWNBl7-AKvj1AAAwWD4VeAg577.jpg

私钥:须要和 /etc/fdfs/http.conf 中的 http.anti_steal.secret_key 值统一
工夫戳:单位秒

2、java生成token

/**     * 生成token     *     * @param fileId          the filename return by FastDFS server,不能含有组     * @param timestampSecond 工夫戳 单位秒     * @return token     * @throws NoSuchAlgorithmException     */    private String generatorToken(String fileId, Long timestampSecond) throws NoSuchAlgorithmException {        // 须要去掉 group        fileId = fileId.substring(fileId.indexOf("/") + 1);        byte[] bsFilename = fileId.getBytes(StandardCharsets.UTF_8);        byte[] bsTimestamp = timestampSecond.toString().getBytes(StandardCharsets.UTF_8);        // thisisasecuritykey 须要和 /etc/fdfs/http.conf 中的 http.anti_steal.secret_key 值统一        byte[] bsKey = "thisisasecuritykey".getBytes(StandardCharsets.UTF_8);        byte[] buff = new byte[bsFilename.length + bsKey.length + bsTimestamp.length];        System.arraycopy(bsFilename, 0, buff, 0, bsFilename.length);        System.arraycopy(bsKey, 0, buff, bsFilename.length, bsKey.length);        System.arraycopy(bsTimestamp, 0, buff, bsFilename.length + bsKey.length, bsTimestamp.length);        return md5(buff);    }    public static String md5(byte[] source) throws NoSuchAlgorithmException {        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};        java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");        md.update(source);        byte tmp[] = md.digest();        char str[] = new char[32];        int k = 0;        for (int i = 0; i < 16; i++) {            str[k++] = hexDigits[tmp[i] >>> 4 & 0xf];            str[k++] = hexDigits[tmp[i] & 0xf];        }        return new String(str);    }

3、测试

3.1 带正确token拜访

3.2 带谬误token拜访

这个中央返回的图片是 http.anti_steal.token_check_fail = /data/fastdfs/401.jpg 这个配置中配置的图片。

4、我的项目代码

https://gitee.com/huan1993/spring-cloud-parent/tree/master/springboot/springboot-fastdfs

5、参考链接

  1. 应用FastDFS的内置防盗链性能官网文章 http://bbs.chinaunix.net/thread-1916999-1-1.html
  2. fastdfs faq http://bbs.chinaunix.net/thread-1920470-1-1.html