返回介绍

12.3 范例 2:防止交叉引用

发布于 2025-04-22 20:10:04 字数 2697 浏览 0 评论 0 收藏

心怀叵测的竞争对手有可能通过交叉引用“窃取”你的网站资产,例如,将你的资料公然放在他的网站上,好像那些东西原本就属于他的一样。如果通过编程控制,使得只有当 referer 标题中包含你的域名时才发出资源,就可以防止那种情况发生。当然,那些心意坚决的窃贼仍然有办法下载到你的东西,但是绝不会像以前那样不费吹灰之力就能得到。

download 应用程序利用清单 12.4 中的 ImageController 类,使得仅当 referer 标题不为 null 时,才将图片发送给浏览器。这样可以防止仅在浏览器中输入网址就能下载图片的情况发生。

清单 12.4 ImageController 类

package controller;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ImageController {

  private static final Log logger =
      LogFactory.getLog(ImageController.class);

  @RequestMapping(value="/image_get/{id}", method = RequestMethod.GET)
  public void getImage(@PathVariable String id,
      HttpServletRequest request, HttpServletResponse response,
      @RequestHeader String referer) {
    if (referer != null) {
      String imageDirectory = request.getServletContext().
          getRealPath("/WEB-INF/image");
      Path file = Paths.get(dataDirectory, id + ".jpg");
      if (Files.exists(file)) {
        response.setContentType("image/jpg");
        try {
          Files.copy(file, response.getOutputStream());
        } catch (IOException ex) {
          e.printStackTrace();
        }
      }
    }
  }
}

原则上,ImageController 类的作用与 ResourceController 无异。getImage 方法开头处的 if 语句,可以确保只有当 referer 标题不为 null 时,才发出图片。

利用清单 12.5 中的 images.html 文件,可以对这个应用程序进行测试。

清单 12.5 images.html 文件

<!DOCTYPE html>
<html>
<head>
  <title>Photo Gallery</title>
</head>
<body>
<img src="get-image/1"/>
<img src="get-image/2"/>
<img src="get-image/3"/>
<img src="get-image/4"/>
<img src="get-image/5"/>
<img src="get-image/6"/>
<img src="get-image/7"/>
<img src="get-image/8"/>
<img src="get-image/9"/>
<img src="get-image/10"/>
</body>
</html>

要想看到 ImageServlet 的效果,请在浏览器中打开以下网址:

http://localhost:8080/download/images.html

图 12.1 展示了使用 ImageServlet 后的效果。

图片 1

图 12.1 使用 ImageServlet 后的效果

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。