X-Frame-Options 有三个值:
DENY
表示该页面不允许在 frame 中展示,即便是在相同域名的页面中嵌套也不允许。
SAMEORIGIN
表示该页面可以在相同域名页面的 frame 中展示。
ALLOW-FROM uri
表示该页面可以在指定来源的 frame 中展示。
SpringSecurity对应的实现策略
image.pngWhiteListedAllowFromStrategy 不生效?
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends DefaultWebSecurityConfigurer {
@Override
public void configure(HttpSecurity http) throws Exception {
super.configure(http);
//disable 默认策略
http.headers().frameOptions().disable();
//允许同源
// http.headers().frameOptions().sameOrigin();
//指定单个域名
//http.headers().addHeaderWriter(new XFrameOptionsHeaderWriter(new StaticAllowFromStrategy(new URI("https://cityradar.umeng.com"))));
//域名白名单
http.headers().addHeaderWriter(new XFrameOptionsHeaderWriter(
new WhiteListedAllowFromStrategy(
Arrays.asList(
"https://a.test.com",
"https://b.test.com",
"https://c.test.com"
)
)
));
}
}
看了一下X-Frame-Options还是DENY, 说明设置的白名单没有写入成功
源码分析
XFrameOptionsHeaderWriter负责写入header
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
if (XFrameOptionsHeaderWriter.XFrameOptionsMode.ALLOW_FROM.equals(this.frameOptionsMode)) {
String allowFromValue = this.allowFromStrategy.getAllowFromValue(request);
if (XFrameOptionsHeaderWriter.XFrameOptionsMode.DENY.getMode().equals(allowFromValue)) {
response.setHeader("X-Frame-Options", XFrameOptionsHeaderWriter.XFrameOptionsMode.DENY.getMode());
} else if (allowFromValue != null) {
response.setHeader("X-Frame-Options", XFrameOptionsHeaderWriter.XFrameOptionsMode.ALLOW_FROM.getMode() + " " + allowFromValue);
}
} else {
response.setHeader("X-Frame-Options", this.frameOptionsMode.getMode());
}
}
两个关键的地方:先获取allowFromValue,再设置header
1. String allowFromValue = this.allowFromStrategy.getAllowFromValue(request);
2. response.setHeader("X-Frame-Options", XFrameOptionsHeaderWriter.XFrameOptionsMode.ALLOW_FROM.getMode() + " " + allowFromValue);
allowFromValue如何获取
AbstractRequestParameterAllowFromStrategy中主要代码可以看出,是从request中的参数中获取,参数名默认是x-frames-allow-from
private String allowFromParameterName = "x-frames-allow-from";
public String getAllowFromValue(HttpServletRequest request) {
String allowFromOrigin = request.getParameter(this.allowFromParameterName);
if (this.log.isDebugEnabled()) {
this.log.debug("Supplied origin '" + allowFromOrigin + "'");
}
return StringUtils.hasText(allowFromOrigin) && this.allowed(allowFromOrigin) ? allowFromOrigin : "DENY";
}
那岂不是可以随便传AllowFromValue了?注意这句
this.allowed(allowFromOrigin) ? allowFromOrigin : "DENY";
WhiteListedAllowFromStrategy策略中实现了此方法, 只有设置的AllowFromValue和白名单中的域名匹配上才会去设置
protected boolean allowed(String allowFromOrigin) {
return this.allowed.contains(allowFromOrigin);
}
总结:
要想使WhiteListedAllowFromStrategy生效,必须在请求参数中加上x-frames-allow-from参数,并且需要和WhiteListedAllowFromStrategy中设置的白名单匹配
网友评论