我正在研究 SpringBoot api 并使用具有以下属性设置的 H2 数据库。
spring.h2.console.enabled=true
spring.datasource.name=test
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.datasource.initialization-mode = embedded
spring.datasource.url=jdbc:h2:mem:test
spring.jpa.hibernate.ddl-auto = update
当我想使用浏览器通过“http://localhost:8082/h2-console”查看H2数据库控制台时,浏览器中会打开一个屏幕,其中包含连接和测试连接按钮。当我单击“测试连接”时,它返回成功,但是当单击“连接”按钮时,出现错误,本地主机拒绝连接。
将这两行添加到您的 Spring 安全文件中,就可以开始了。
http.csrf().disable();
http.headers().frameOptions().disable();
默认情况下,Spring Security 会禁用 iframe 内的渲染,因为允许将网页添加到框架中可能会产生安全问题,例如 Clickjacking。由于 H2 控制台在框架内运行,因此在启用 Spring 安全性时,必须显式禁用框架选项,以使 H2 控制台正常工作。
http.headers().frameOptions().disable();
一般来说,X-Frame-Options有两个可能的指令,即 DENY 或 SAMEORIGIN,因此以下配置也可用于受限但安全的访问。
headers().frameOptions().sameOrigin();
这允许页面显示在与页面本身同源的框架中
除了@Alien的回复,我还必须添加
http.csrf().disable();
。
添加了以下第一行 application.properties
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
还在 pom.xml 上添加了以下内容
<build>
<plugins>
<plugin>
<configuration>
<jdbc>
<driver>org.h2.Driver</driver>
<url>jdbc:h2:~/test</url>
</jdbc>
</configuration>
</plugin>
</plugins>
<build>
对于 Spring Boot 3+ 和 Spring Security 6,请将以下行添加到您的 SecurityFilterChain Bean 中。新版本的 Spring security 大量使用 lambda 表达式进行配置。以下几行使用 Java 8+ 中的方法引用。
.csrf(AbstractHttpConfigurer::disable)
.headers(httpSecurityHeadersConfigurer -> {
httpSecurityHeadersConfigurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable);
})
上面没有方法引用的代码如下。
.csrf(httpSecurityCsrfConfigurer -> httpSecurityCsrfConfigurer.disable())
.headers(httpSecurityHeadersConfigurer -> {
httpSecurityHeadersConfigurer.frameOptions(frameOptionsConfig -> {
frameOptionsConfig.disable();
});
})
但是,除了上述代码之外,您还需要正确配置 h2 数据库,在 application.properties 文件中启用 h2-console,并允许在 SecurityFilterChain Bean 中访问 h2-console,如下所示。
.authorizeHttpRequests(registry -> {
registry.requestMatchers("/console/**").permitAll();
})