H2-Database 控制台无法使用 Spring-Security 打开

Mar*_*arc 6 java h2 spring-security spring-boot

我正在使用H2-Databaseand Spring Security,但无法在浏览器中打开它http://localhost:8080/h2-console

这是我的pom.xml(仅H2条目)

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)

在这里我的application.properties

spring.datasource.url=jdbc:h2:file:/data/noNameDB
spring.h2.console.enabled=true
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=admin
spring.datasource.password=admin
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.path=/h2-console
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jackson.serialization.fail-on-empty-beans=false
Run Code Online (Sandbox Code Playgroud)

这是我的SecurityConfig.java

import com.example.noName.security.JwtAuthenticationEntryPoint;
import com.example.noName.security.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;



@Configuration
@EnableWebSecurity
public class SecurityConfig {


    private static final String[] AUTH_WHITE_LIST = {
            "/v3/api-docs/**",
            "/swagger-ui/**",
            "/v2/api-docs/**",
            "/swagger-resources/**",
            "/h2-console/**",
            "/console/**",
            "/account/**"
    };

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Bean
    public JwtAuthenticationFilter jwtAuthenticationFilter() {
        return new JwtAuthenticationFilter();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration authConfig) throws Exception {
        return authConfig.getAuthenticationManager();
    }



    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeHttpRequests()
                .requestMatchers(AUTH_WHITE_LIST)
                .permitAll()
                .and()
                .headers()
                .frameOptions()
                .disable()
                .and()
                .authorizeHttpRequests()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic()
                .and()
                .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .httpBasic();

        return http.build();
    }

}

Run Code Online (Sandbox Code Playgroud)

如果我尝试通过以下方式访问控制台,控制台中会显示以下内容http://localhost:8080/h2-console

INFO 3664 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
INFO 3664 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
INFO 3664 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 1 ms
Run Code Online (Sandbox Code Playgroud)

我已经尝试了在互联网上可以找到的所有内容。

有趣的是,“异常处理”适用于Swagger. 如果我尝试通过以下方式访问数据库:

http://localhost:8080/h2-console
Run Code Online (Sandbox Code Playgroud)

我总是收到错误:

401 - Unauthorized
Run Code Online (Sandbox Code Playgroud)

每一个都很奇怪,因为访问是在SecurityConfig.

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
            .cors()
            .and()
            .csrf()
            .disable()
            .exceptionHandling()
            .authenticationEntryPoint(jwtAuthenticationEntryPoint)
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeHttpRequests()
            .requestMatchers(AUTH_WHITE_LIST)
            .permitAll()
            .and()
            .headers()
            .frameOptions()
            .disable()
            .and()
            .authorizeHttpRequests()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic()
            .and()
            .addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
            .httpBasic();

    return http.build();
}
Run Code Online (Sandbox Code Playgroud)

我可以通过内部数据库测试访问数据库。这是由 提供的Intellij

然而working/editing在数据库中是不可能通过这个。

和:

如果我将其更改AUTH_WHITE_LIST为这个,它就会起作用。

private static final String[] AUTH_WHITE_LIST = {
       "/**"
};
Run Code Online (Sandbox Code Playgroud)

xer*_*593 20

我可以用spring-boot:3.0.0(web, security, h2, ...)重现并且:

return http
        .authorizeHttpRequests()
        .requestMatchers("/h2-console/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .and()
        .csrf().ignoringRequestMatchers("/h2-console/**")
        .and()
        .headers().frameOptions().sameOrigin()
        .and()
        .build();
Run Code Online (Sandbox Code Playgroud)

/h2-console仍然受到保护!)

使固定:

(弹簧引导方式):

import static //
org.springframework.boot.autoconfigure.security.servlet.PathRequest.toH2Console; // !
...
  .requestMatchers(toH2Console()).permitAll()
  ...
  .csrf().ignoringRequestMatchers(toH2Console())
Run Code Online (Sandbox Code Playgroud)

参考文献:

它内部使用:

new AntPathRequestMatcher(h2ConsoleProperties.get().getPath() + "/**");
Run Code Online (Sandbox Code Playgroud)

requestMatcher(String... paths)这似乎与( )不同/更好AbstractRequestMatcherRegistry,它调用了这个(用method==null):

public C requestMatchers(HttpMethod method, String... patterns) {
   List<RequestMatcher> matchers = new ArrayList<>();
   if (mvcPresent) {
      matchers.addAll(createMvcMatchers(method, patterns)); // <- we land here obviously
   } else {
      matchers.addAll(RequestMatchers.antMatchers(method, patterns));     
   }
  return requestMatchers(matchers.toArray(new RequestMatcher[0]));
}
Run Code Online (Sandbox Code Playgroud)

... 备择方案:

  • RequestMatchers.antMatcher(null, pathToH2+"/**")
  • AntPathRequestMatcher(对于忽略大小写(以及所有http 方法),更喜欢使用构造函数而不是工厂;)
  • MvcMatcher(对于 h2-console 来说这是不可能的,因为它不是 mvc;(

但是/和

我不会在生产中这样做(不安全)


小智 5

根据 spring 博客上关于没有 WebSecurityConfigurerAdapter 的 Spring Security 的帖子,我们可以使用 WebSecurityCustomize 来忽略安全性中的整个端点。这种情况非常适合发布 h2 控制台,因为在安全的情况下我们只想忽略这个特定的端点。工作示例:

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring().requestMatchers(new AntPathRequestMatcher(H2_CONSOLE_PATH));
}
Run Code Online (Sandbox Code Playgroud)

这就是我们所需要的,可能是解决这个问题的最干净的解决方案。