x-frame-options

背景

在接入内容平台的时候, 内容平台使用iframe来嵌入ugc的帖子详情页, 让用户可以预览帖子详情。 但是帖子详情页不支持iframe的嵌入, 导致出现如下错误: ”star.aliexpress.com 拒绝了我们的连接请求。“ 具体如下:

原因

这是因为帖子详情页不支持iframe嵌入, 这个主要是因为spring boot默认为了安全, 默认不让网页支持嵌入, 帮助用户对抗点击劫持。

解决办法

X-Frame-Options 有三个值:
DENY
表示该页面不允许在 frame 中展示,即便是在相同域名的页面中嵌套也不允许。
SAMEORIGIN
表示该页面可以在相同域名页面的 frame 中展示。
ALLOW-FROM uri
表示该页面可以在指定来源的 frame 中展示。

spring boot支持EnableWebSecurity 这个anotation来设置不全的安全策略。 具体如下:

import com.alibaba.spring.websecurity.DefaultWebSecurityConfigurer;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.header.writers.frameoptions.WhiteListedAllowFromStrategy;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;

import java.util.Arrays;

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends DefaultWebSecurityConfigurer {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
       //disable 默认策略。 这一句不能省。 
        http.headers().frameOptions().disable();
       //新增新的策略。 
        http.headers().addHeaderWriter(new XFrameOptionsHeaderWriter(
                new WhiteListedAllowFromStrategy(
                        Arrays.asList("http://itaobops.aliexpress.com", "https://cpp.alibaba-inc.com",
                                "https://pre-cpp.alibaba-inc.com"))));
    }
}

上面是支持ALLOW-FROM uri的设置方式。

其他设置方式比较简单。 下面是支持SAMEORIGIN的设置方式:

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends DefaultWebSecurityConfigurer {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.headers().frameOptions().sameOrigin();

    }
}

下面是支持完全放开的方式:


@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends DefaultWebSecurityConfigurer {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.headers().frameOptions().disable();
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容