.headers().frameOptions().disable() 是如何工作的?

问题描述 投票:0回答:2

关于

Spring Security
让、控制和访问
h2
Web 控制台

我读了这两篇文章:

总而言之,必须使用以下内容(以某种方式“改进”):

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .mvcMatchers("/admin/**").hasRole("ADMIN")
            ...
            .mvcMatchers("/h2-console/**").hasRole("ADMIN")
            .and()
        .csrf().ignoringAntMatchers("/h2-console/**")
            .and()
        .headers().frameOptions().disable()
            .and()

从上面来看,出于安全原因,最好使用

.csrf().ignoringAntMatchers("/h2-console/**")
而不是
csrf().disable()
,因为禁用点仅适用于
/h2-console/
,后者是全局的,不建议使用。

直到这里我都很好。我能够看到 登录过程发生并且用户具有所需角色后,H2 Web 控制台。

enter image description here

现在是强制使用

.headers().frameOptions().disable()
,如果不使用会发生以下情况:

enter image description here

当鼠标光标位于任何内部块上时,

localhost refused to connect
消息会出现在任何内部块上

我的疑问是:

  1. .headers().frameOptions().disable()
    如何运作?
  2. 在生产环境中使用这句话安全吗?考虑之间的区别
    .csrf().ignoringAntMatchers("/h2-console/**")
    csrf().disable()
    ,前者是特定的,后者是“全局的”(不推荐)。因此,也许可以使用比
    .headers().frameOptions().disable()
    更好的特定配置(乍一看对我来说是“全局”配置),仅适用于
    /h2-console/
  3. .headers().frameOptions().disable()
    是否会对其他
    configure(HttpSecurity http)
    配置产生直接或间接的负面影响? (主要用于生产)
spring-security h2
2个回答
17
投票

首先,让我们看一下 X-Frame-Options 响应标头。
此标头可用于指示是否允许浏览器以

<frame>
<iframe>
方式呈现页面。
网站可以使用它来避免点击劫持攻击,确保其内容不嵌入到其他网站中。

Spring Security 默认将 X-Frame-Options 响应标头设置为

DENY

这告诉浏览器该页面无法在框架中显示,无论站点尝试这样做。
由于 H2 控制台 UI 使用
<frame>
元素,因此这些元素不会被渲染,您将看到您在问题中共享的错误屏幕。

Spring Security 允许您使用 Security DSL 中的

.headers().frameOptions()
自定义此行为。
如果您选择通过设置
.headers().frameOptions().disable()
来禁用 X-Frame-Options 标头(不推荐),那么 Spring Security 不会将 X-Frame-Options 标头添加到响应中。
这意味着您的应用程序可能会在框架中呈现,并且也可能容易受到点击劫持攻击

对于此用例,将 X-Frame-Options 设置为

SAMEORIGIN
就足够了,而不是禁用它。

http
    .headers(headers -> headers
        .frameOptions(frameOptions -> frameOptions
            .sameOrigin()
        )
    )

这告诉浏览器该页面只能显示在与页面本身同源的框架中。

由于 H2 控制台 UI 中的框架(如

http://localhost:8080/h2-console/tables.do
)与 H2 控制台(
http://localhost:8080/h2-console
)同源,浏览器将允许它们显示。

但是,如果另一个(可能是恶意的)网站尝试嵌入页面,浏览器将不允许这样做。


0
投票
@Configuration
@EnableWebSecurity

公共类 WebSecurityConfig {

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        // ...
        .headers(headers -> headers
            .frameOptions(frameOptions -> frameOptions
                .disable()
            )
        );
    return http.build();
}

}

© www.soinside.com 2019 - 2024. All rights reserved.