问题名称
X-Frame-Options响应头缺失,导致攻击者使用一个或多个透明的iframe覆盖在正常网页上,诱使用户在网页上进行操作,当用户在不知情的情况下点击透明的iframe页面时,用户的操作已被劫持到攻击者事先设计的恶意按钮或链接上
解决方案
设置 X-Frame-Options
响应头
在 Spring Boot 中可以通过配置 WebSecurityConfigurerAdapter
或者使用 Filter
来设置响应头
使用 WebSecurityConfigurerAdapter
配置类
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.headers()
.frameOptions()
.sameOrigin(); // 设置 X-Frame-Options 为 SAMEORIGIN
}
}
使用 Filter
设置响应头
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@Order(1)
public class AddResponseHeaderFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("X-Frame-Options", "SAMEORIGIN");
chain.doFilter(request, response);
}
}
设置 nginx
配置
#添加头文件
add_header X-Frame-Options SAMEORIGIN always;
修复验证:
X-Frame-Options
响应头的配置
X-Frame-Options
是一个 HTTP 响应头,允许网站控制是否允许页面在 <frame>
, <iframe>
, <embed>
或 <object>
中加载。通过设置 X-Frame-Options
,可以指定以下三个值:
- DENY:表示页面不能在任何 frame 中显示,包括相同域名的页面。
- SAMEORIGIN:表示页面可以在相同域名页面的 frame 中显示。
- ALLOW-FROM uri:表示页面可以在指定来源的 frame 中显示。
为了防止点击劫持,建议设置 X-Frame-Options
响应头为 DENY
或 SAMEORIGIN
,具体选择取决于网站架构和需求