启用SpringSecurity后H2数据库web控制台403和空白页面的问题

638 阅读1分钟

问题1. Springboot项目启用SpringSecurity后访问H2数据库web控制台时产生403的问题

image.png

问题2. 403问题解决后允许访问,但是产生空白页面不渲染组件的问题

image.png

解决方案

1. 问题1:

Spring Security 默认开启了 CSRF 的保护,H2 相关的请求需要携带 CSRF Token 及相关参数,所以访问时候出现了 403 。

方案1

(推荐)使SpringSecurity的SCRF保护忽略掉H2数据库的路径。

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().ignoringAntMatchers("/h2/**");
    }
}

忽略路径中的h2是你在Springboot配置文件中给H2数据库配置的path

spring:
  h2:
    console:
      enabled: true
      path: /h2

  datasource:
    driver-class-name: org.h2.Driver
    schema: classpath:db/schema-h2.sql
    data: classpath:db/data-h2.sql
    url: jdbc:h2:mem:test
    username: root
    password: test
方案2

(不推荐)彻底关闭CSRF保护

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}

2. 问题2:

Spring Security 默认页面不允许 iframe (不安全),会在响应头返回:

X-Frame-Options:DENY

导致 H2Database 访问页面空白。

方案1

直接禁用 frameOptions()

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .headers().frameOptions().disable();
    }
}
方案2

允许同源使用 iframe 

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .headers().frameOptions().sameOrigin();
    }
}

参考文章www.jianshu.com/p/925d5aece…