背景
在接入內容平台的時候, 內容平台使用iframe來嵌入ugc的帖子詳情頁, 讓用戶可以預覽帖子詳情。 但是帖子詳情頁不支持iframe的嵌入, 導致出現如下錯誤: ”star.aliexpress.com 拒絕了我們的連接請求。“ 具體如下:
image.png
原因
這是因為帖子詳情頁不支持iframe嵌入, 這個主要是因為spring boot默認為了安全, 默認不讓網頁支持嵌入, 幫助用戶對抗點擊劫持。
image.png
解決辦法
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();
}
}
1人點贊
其他
作者:YDDMAX_Y
鏈接:https://www.jianshu.com/p/9ec724f4e3ae
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。