防盗链的基本原理与实现

来源:互联网 发布:手机修改软件版本 编辑:程序博客网 时间:2024/05/08 17:11

1.  我的实现防盗链的做法,也是参考该位前辈的文章。基本原理就是就是一句话:通过判断request请求头的refer是否来源于本站。(当然请求头是来自于客户端的,是可伪造的,暂不在本文讨论范围内)。

2.  首先我们去了解下什么是HTTP Referer。简言之,HTTP Referer是header的一部分,当浏览器向web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器籍此可以获得一些信息用于处理。比如从我主页上链接到一个朋友那里,他的服务器就能够从HTTP Referer中统计出每天有多少用户点击我主页上的链接访问他的网站。(注:该文所有用的站点均假设以http://blog.csdn.net为例)

假如我们要访问资源:http://blog.csdn.net/Beacher_Ma 有两种情况:

1.  我们直接在浏览器上输入该网址。那么该请求的HTTP Referer 就为null

2.  如果我们在其他其他页面中,通过点击,如 http://www.csdn.net 上有一个http://blog.csdn.net/Beacher_Ma 这样的链接,那么该请求的HTTP Referer 就为http://www.csdn.net

3.  知道上述原理后,我们可以用Filter去实现这个防盗链功能。网上的做法多是用列举的方式去做的,而我这里是用正则去做,相对比较灵活点,另外,我效仿了spring的filter做法,加了个shouldBeFilter的方法,考虑到,比如假如你要拦截*.Action的一部分方法,而不是全部时,我们就可以先看看请求的URL是否shouldBeFilter,如果不是的话,那么就直接放行,在效率上有所提高。废话不说,直接上代码吧。

//防盗链filter

publicclass PreventLinkFilterimplements Filter {

    privatestatic Loggerlogger = LoggerFactory

           .getLogger(PreventLinkFilter.class);

    //限制访问地址列表正则

    privatestatic List<Pattern>urlLimit =new ArrayList<Pattern>();

    //允许访问列表

    privatestatic List<String>urlAllow =new ArrayList<String>();

    //错误地址列表

    privatestatic StringurlError ="";

 

    //必须过Filter的请求

    protectedboolean shouldBeFilter(HttpServletRequest request)

           throws ServletException {

       String path = request.getServletPath();

       for (int i = 0; i <urlLimit.size(); i++) {

           Matcher m = urlLimit.get(i).matcher(path);

           if (m.matches()) {

              logger.debug("当前的Path{}" + path + "必须进行过滤");

              returntrue;

           }

       }

       returnfalse;

    }

 

    publicvoid destroy() {

       //TODO Auto-generated method stub

 

    }

 

    publicvoid doFilter(ServletRequest request, ServletResponse response,

           FilterChain chain) throws IOException, ServletException {

       HttpServletRequest httpRequest = (HttpServletRequest) request;

       HttpServletResponse httpResponse = (HttpServletResponse) response;

       if (null == httpRequest ||null == httpResponse) {

           return;

       }

       //放行不符合拦截正则的Path

       if (!shouldBeFilter(httpRequest)) {

           chain.doFilter(request, response);

           return;

       }

 

       String requestHeader = httpRequest.getHeader("referer");

       if (null == requestHeader) {

           httpResponse.sendRedirect(urlError);

           return;

       }

       for (int i = 0; i <urlAllow.size(); i++) {

           if (requestHeader.startsWith(urlAllow.get(i))) {

              chain.doFilter(httpRequest, httpResponse);

              return;

           }

       }

       httpResponse.sendRedirect(urlError);

       return;

    }

 

    publicvoid init(FilterConfig fc)throws ServletException {

       logger.debug("防盗链配置开始...");

       String filename;

       try {

           filename = fc.getServletContext().getRealPath(

                  "/WEB-INF/classes/preventLink.properties");

           File f = new File(filename);

           InputStream is = new FileInputStream(f);

           Properties pp = new Properties();

           pp.load(is);

           //限制访问的地址正则

           String limit = pp.getProperty("url.limit");

           //解析字符串,变成正则,放在urlLimit列表中

           parseRegx(limit);

           //不受限的请求头

           String allow = pp.getProperty("url.allow");

           //将所有允许访问的请求头放在urlAllow列表中

           urlAllow = parseStr(urlAllow, allow);

           urlError = pp.getProperty("url.error");

       } catch (Exception e) {

           e.printStackTrace();

       }

 

    }

 

    privatevoid parseRegx(String str) {

       if (null != str) {

           String[] spl = str.split(",");

           if (null != spl) {

              for (int i = 0; i < spl.length; i++) {

                  Pattern p = Pattern.compile(spl[i].trim());

                  urlLimit.add(p);

              }

           }

       }

 

    }

    private List<String> parseStr(List<String> li, String str) {

       if (null == str || str.trim().equals("")) {

           returnnull;

       }

       String[] spl = str.split(",");

       if (null != spl && spl.length > 0) {

           li = Arrays.asList(spl);

       }

       return li;

    }

}

文件/WEB-INF/classes/preventLink.properties

##用于限制的url正则,用逗号分隔多个(在这里我拦截了诸如/csdn/index!beacher_Ma.action,/csdn/index!beacher_Ma.action?adsfdf)

url.limit=/.+/index/!.+//.action.*,/index/!.+.action?.+

##这里是Http Refer是否以指定前缀开始,前两个是本地调试用的。。

url.allow=http://127.0.0.1,http://localhost,http://www.csdn.NET

##这里是被盗链后,response到以下的错误页面

url.error=http://www.csdn.Net/error.html

参考文章:http://shen198623.javaeye.com/blog/243330

   这篇文章是拦截所有的请求的,他fileter中的url-pattern是/*,这样的话,连/css /jpg等都话被filter拦截到,要么在里面进行shouldBeFilter的判断,要么就在url-pattern中缩写拦截范围,这个要看具体你要拦截什么样的请求,另外图片防盗链,下载反盗链也是一样的原理的。

0 0