关于
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 控制台。
现在是强制使用
.headers().frameOptions().disable()
,如果不使用会发生以下情况:
当鼠标光标位于任何内部块上时,
localhost refused to connect
消息会出现在任何内部块上
我的疑问是:
.headers().frameOptions().disable()
如何运作?.csrf().ignoringAntMatchers("/h2-console/**")
和 csrf().disable()
,前者是特定的,后者是“全局的”(不推荐)。因此,也许可以使用比 .headers().frameOptions().disable()
更好的特定配置(乍一看对我来说是“全局”配置),仅适用于 /h2-console/
.headers().frameOptions().disable()
是否会对其他 configure(HttpSecurity http)
配置产生直接或间接的负面影响? (主要用于生产)首先,让我们看一下 X-Frame-Options 响应标头。
此标头可用于指示是否允许浏览器以
<frame>
或 <iframe>
方式呈现页面。Spring Security 默认将 X-Frame-Options 响应标头设置为
DENY
。<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
)同源,浏览器将允许它们显示。
但是,如果另一个(可能是恶意的)网站尝试嵌入页面,浏览器将不允许这样做。
@Configuration
@EnableWebSecurity
公共类 WebSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// ...
.headers(headers -> headers
.frameOptions(frameOptions -> frameOptions
.disable()
)
);
return http.build();
}
}