如何阻止iframe访问网站?

3
我注意到一些网站因安全原因拒绝从iFrames访问其注册和登录页面,我认为这是一个好主意。
我想知道他们需要哪些设置才能做到这一点,因为我也希望在我的网站上实现同样的功能。该网站使用Java构建并在Apache Tomcat上运行。
如果有人知道如何做到这一点,如果您能分享一下就太好了。
3个回答

4

这是我使用过并且有效的方法。我从这里获取了所有的东西。

在web.xml中添加以下之一,根据您想要实施的策略:

<display-name>OWASP ClickjackFilter</display-name>
    <filter>
        <filter-name>ClickjackFilterDeny</filter-name>
        <filter-class>org.owasp.filters.ClickjackFilter</filter-class>
        <init-param>
            <param-name>mode</param-name>
            <param-value>DENY</param-value>
        </init-param>
    </filter>

    <filter>
        <filter-name>ClickjackFilterSameOrigin</filter-name>
        <filter-class>org.owasp.filters.ClickjackFilter</filter-class>
        <init-param>
            <param-name>mode</param-name>
            <param-value>SAMEORIGIN</param-value>
        </init-param>
    </filter>

     <!--  use the Deny version to prevent anyone, including yourself, from framing the page -->
    <filter-mapping> 
        <filter-name>ClickjackFilterDeny</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- use the SameOrigin version to allow your application to frame, but nobody else
    <filter-mapping> 
        <filter-name>ClickjackFilterSameOrigin</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    -->

    ...

然后在Java代码中:

public class ClickjackFilter implements Filter 
{

    private String mode = "DENY";

    /**
     * Add X-FRAME-OPTIONS response header to tell IE8 (and any other browsers who
     * decide to implement) not to display this content in a frame. For details, please
     * refer to http://blogs.msdn.com/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx.
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse res = (HttpServletResponse)response;
        //If you have Tomcat 5 or 6, there is a known bug using this code.  You must have the doFilter first:
        chain.doFilter(request, response);
        res.addHeader("X-FRAME-OPTIONS", mode );            
        //Otherwise use this:
        //res.addHeader("X-FRAME-OPTIONS", mode );          
        //chain.doFilter(request, response);

    }

    public void destroy() {
    }

    public void init(FilterConfig filterConfig) {
        String configMode = filterConfig.getInitParameter("mode");
        if ( configMode != null ) {
            mode = configMode;
        }
    }

谢谢!只是要补充一下,Java代码需要编译成一个.jar文件并放置在Tomcat/lib目录中。 - gordon613

3

谢谢,我现在正在查看。 :) - diggersworld
几天前,我试图在iframe中嵌入Gmail页面,以获取用户电子邮件地址(点击劫持攻击!),但是x-frame-options让我感到沮丧!;) - try2fly.b4ucry

0
你可以用JavaScript检测iframe。
location.href != top.location.href -> iframe.

您也可以使用“X-Frame-Options”HTTP标头。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接