通过Referer请求头实现防盗链
盗链: 其他站点通过超链接等连接到我们自己的站点窃取我们的资源的行为就称之为盗链.
Referer请求头: 代表当前访问时从哪个网页连接过来的.
Example:
加入我们有一个新闻网站,在相关人员的努力下终于采访到一个重磅新闻,因此我们将该新闻放置到我们网站的官方首页上,通过超链接进行访问.
<a href="${pageContext.request.contextPath }/NewsServlet">重磅新闻</a>
@WebServlet(“/NewsServlet”)
public class NewsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html;charset=utf-8”);
response.getWriter().write(“习大大吃包子….”);
}
public class NewsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html;charset=utf-8”);
response.getWriter().write(“习大大吃包子….”);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
现在有一个其他网站, blog.ytso.com 没有新闻,看见了该新闻很受大家喜欢就在自己的主页上加了如下超链接
<a href=”http://localhost/Day04-Response-Request/NewsServlet”>特大新闻</a>
这样,我们费尽努力得到的资源就被别人轻易的窃取了,这就是盗链行为.
为了防止该行为我们可以通过 Referer请求头实现防盗链:
修改NewsServlet如下:
@WebServlet(“/NewsServlet”)
public class NewsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html;charset=utf-8”);
String referer = request.getHeader(“Referer”);
if(referer == null || “”.equals(referer) || !referer.contains(“localhost/”)) {
response.sendRedirect(request.getContextPath() + “/index.jsp”);
return;
}
response.getWriter().write(“习大大吃包子….”);
}
public class NewsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(“text/html;charset=utf-8”);
String referer = request.getHeader(“Referer”);
if(referer == null || “”.equals(referer) || !referer.contains(“localhost/”)) {
response.sendRedirect(request.getContextPath() + “/index.jsp”);
return;
}
response.getWriter().write(“习大大吃包子….”);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
当Referer未存在或者是从其他站点访问我们资源的时候就直接重定向到我们的主页,这样既可以防止我们的资源被窃取, 而且可以将其他试图盗链的站点的用户慢慢转化为我们站点的用户.
注意: 重定向之后要return, 否则资源也会被窃取.
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/aiops/6297.html