Spring Boot 中使用 H2 數據庫 : https://yuanyu.blog.csdn.net/article/details/106354143
1 加依賴
pom.xml
<!-- security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- db -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
2 寫配置
application.properties
############################################################
#
# h2 配置 http://localhost:6969/h2-console
#
############################################################
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:test_db;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=root
spring.datasource.password=123456
############################################################
#
# spring data 配置
#
############################################################
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true
3. 開放權限
配置 spring security 不要攔截,h2後臺管理界面
http.authorizeRequests()
.antMatchers("/h2-console/**").permitAll(); // 放行 h2 後臺管理界面
spring security 默認是啓用了CSRF防護的,但是 h2 的後臺管理的請求需要攜帶 CSRF 口令之類的參數,因此會被 spring security 攔截所以我們需要針對 h2 放開 CSRF 防護
http.csrf().ignoringAntMatchers("/h2-console/**"); // 禁用 H2 控制檯的 CSRF 防護
h2 後臺管理界面採用了 iframe ,而 spring security 默認是禁止了 ifreame 的使用,因此我們也需要針對 h2 開放對 iframe 的限制
http.headers().frameOptions().sameOrigin(); // 允許來自同一來源的 H2 控制檯的請求
寫在一起
http.authorizeRequests()
.antMatchers("/h2-console/**").permitAll() // 放行 H2 的請求
.and().csrf().ignoringAntMatchers("/h2-console/**") // 禁用 H2 控制檯的 CSRF 防護
.and().headers().frameOptions().sameOrigin(); // 允許來自同一來源的 H2 控制檯的請求