X-Frame-Options頭主要是爲了防止站點被別人劫持,iframe引入
nginx配置形式:
add_header X-Frame-Options ALLOWALL; #允許所有域名iframe
add_header X-Frame-Options DENY; #不允許任何域名iframe,包括相同的域名
add_header X-Frame-Options SANEORIGIN; #允許相同域名iframe,如a.test.com允許b.test.com
add_header X-Frame-Options ALLOW-FROM uri; #允許指定域名iframe,
配置可以放入到nginx的 http 或者 server 中
實例:
========================================================================================
其他方案:https://www.jianshu.com/p/9ec724f4e3ae
背景
在接入內容平臺的時候, 內容平臺使用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();
}
}