1,防盗链防止盗用自己服务上的东西。。。
2,XSS服务上有这么一张图:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<form action="postIndex" method="post">
输入内容: <input type="text" name="name"> <br> <input
type="submit">
</form>
<img src="imgs/logo.PNG" alt="">
</body>
</html>
SatetyChain 服务上:<img src="http://127.0.0.1:8080/img/logo.PNG" alt=""> 直接把这张图片引用过来,属于盗图,怎么防止这种情况发生呢?
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<form action="postIndex" method="post">
输入内容: <input type="text" name="name"> <br> <input
type="submit">
</form>
<img src="http://127.0.0.1:8080/imgs/logo.PNG" alt="">
</body>
</html>
3,防盗链技术实现上面的需求,简单来说,还是通过拦截器,拦截请求,查看请求头Referer记录请求来源,可以查看到请求图片的域名,如果不是指定的域名,让其请求失败
测试:
C:\Windows\System32\drivers\etc\hosts
127.0.0.1 www.aiyuesheng.com
package com.aiyuesheng.filter; import java.io.IOException; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value; @WebFilter(filterName = "imgFilter", urlPatterns = "/imgs/*")
public class ImgFilter implements Filter { @Value("${domain.name}")
private String domainName; public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
String referer = req.getHeader("Referer");
if (StringUtils.isEmpty(referer)) {
request.getRequestDispatcher("/imgs/error.png").forward(request, response);
return;
}
String domain = getDomain(referer);
//域名里面如果有端口号,为了测试
String domainTemp = domain.contains(":") ? domain.split(":")[0] : domain;
if (!domainTemp.equals(domainName)) {
request.getRequestDispatcher("/imgs/error.png").forward(request, response);
return;
}
chain.doFilter(request, response);
} /**
* 获取url对应的域名
*
* @param url
* @return
*/
public String getDomain(String url) {
String result = "";
int j = 0, startIndex = 0, endIndex = 0;
for (int i = 0; i < url.length(); i++) {
if (url.charAt(i) == '/') {
j++;
if (j == 2)
startIndex = i;
else if (j == 3)
endIndex = i;
} }
result = url.substring(startIndex + 1, endIndex);
return result;
} public void destroy() { }
}
当有其他服务,盗用图片的时候,会拦截请求,查看RequestHeader 里面的Referer 参数:不是匹配的域名,则重定向error.png