原理】配置http的响应头信息:属性名X-Frame-Options。
可以配置的参数有两个:
X-Frame-Options 响应头有三个可选的值:
DENY:页面不能被嵌入到任何iframe或frame中;
SAMEORIGIN:页面只能被本站页面嵌入到iframe或者frame中;
ALLOW-FROM:页面允许frame或frame加载。
在服务端设置的方式如下:
Java代码:
response.addHeader(“x-frame-options”,”SAMEORIGIN”);
Nginx配置:
add_header X-Frame-Options SAMEORIGIN
Apache配置:
Header always append X-Frame-Options SAMEORIGIN
一般选第二个参数就可以了。
【步骤】
1.在src目录下建一个包,命名为filter。在包里建类名为FrameTao。内容如下:
- package 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.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- public class FrameTao implements Filter {
- public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
- //必须
- HttpServletRequest request = (HttpServletRequest) req;
- HttpServletResponse response = (HttpServletResponse) res;
- //实际设置
- response.setHeader(“x-frame-options”, “SAMEORIGIN”);
- //调用下一个过滤器(这是过滤器工作原理,不用动)
- chain.doFilter(request, response);
- }
- public void init(FilterConfig config) throws ServletException {
- }
- public void destroy() {
- }
- }
2.在web.xml文件下添加以下内容:
- <!– 设置Frame头,防止被嵌套 –>
- <filter>
- <filter-name>FrameFilter</filter-name>
- <filter-class>filter.FrameTao</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>FrameFilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
X-Frame-Options标头不包含在HTTP响应中以防止'ClickJacking'攻击 缺少X-Frame-Options头 缺少X-Content-Type-Options Header 未启用Web浏览器XSS保护 等的解决办法 在tomcat下的conf里的web.xml中增加以下过滤器 <filter> <filter-name>httpHeaderSecurity</filter-name> <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class> <async-supported>true</async-supported> <init-param> <param-name>antiClickJackingEnabled</param-name> <param-value>true</param-value> </init-param> <init-
param> <param-name>antiClickJackingOption</param-name> <param-value>SAMEORIGIN</param-value> </init-param> </filter> <filter-mapping> <filter-name>httpHeaderSecurity</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> 注意:tomcat8以下版本需要下载httpHeaderSecurity.jar这个包
版权声明:本文为xp_lx1原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。