拒绝了我们的连接请求

背景
在接入内容平台的时候, 内容平台使用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
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文地址:https://www.cnblogs.com/suizhikuo/p/12215243.html