how do I set X-Frame-Options response header to allow-from value(s) using spring java config?
Solution 1
I ended up adding my headers statically like below:
http
.headers().frameOptions().disable()
.addHeaderWriter(new StaticHeadersWriter("X-FRAME-OPTIONS", "ALLOW-FROM example1.com"));
Solution 2
//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"))));
Solution 3
You can use X-Content-Security-Policy and Content-Security-Policy instead of X-Frame-Options which give much more flexibility to allow iframe access to multiple domains with wildcard.
Here is an example -
http.csrf().disable()
.headers().addHeaderWriter(new StaticHeadersWriter(
"X-Content-Security-Policy",
"frame-ancestors self *.domain1.com *.domain2.com"))
.and()
.headers().addHeaderWriter(new StaticHeadersWriter(
"Content-Security-Policy",
"frame-ancestors self *.domain1.com *.domain2.com"))
X-Frame-Options value will be discarded.
Kamal Joshi
I love web technologies and am in pursuit of clean, readable, maintainable code and scalable architectures.A variety of web application projects have given me the expertise in Java, Object Oriented Design, Design Patterns, Spring Boot, and Javascript.
Updated on September 23, 2020Comments
-
Kamal Joshi over 3 years
How do I set X-Frame-Options response header with a value of allow-from using spring java config?
http.headers().disable() .addHeaderWriter(new XFrameOptionsHeaderWriter( new WhiteListedAllowFromStrategy( Arrays.asList("https://example1.com", "https://example2.com"))));
In Http Response headers I get:
X-Frame-Options:"ALLOW-FROM DENY".
Why aren't my origins listed in the header value?
-
Kamal Joshi over 7 yearsWith Spring security 4.1 we can do like so, http.headers().frameOptions().disable() .addHeaderWriter( new XFrameOptionsHeaderWriter(new StaticAllowFromStrategy(URI.create("example.com"))));
-
Jinna Balu over 5 yearsThis is not working for me with multiple domains, headers() .addHeaderWriter( new XFrameOptionsHeaderWriter( new WhiteListedAllowFromStrategy( Arrays.asList("test2.com","https://www.test2.com") ) ) )
-
Jinna Balu over 5 yearsThis doen't restrict from the other websites. we can create the XFrame for our website even after adding the addHeaderWriter with frameOptions disabled. DOESN't WORK
-
YGR over 3 yearshttp.headers().contentSecurityPolicy("frame-ancestors self *.domain1.com *.domain2.com") would be even more better.