Spring Security 无法在Sping Boot 3中将h2控制台URL列为白色列表

wpx232ag  于 2023-10-20  发布在  Spring
关注(0)|答案(1)|浏览(172)

我无法在启用spring secutity的情况下访问/h2-console。
下面是配置

@Configuration
@EnableWebSecurity(debug = true)
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests(authorizeRequests -> authorizeRequests
                        .requestMatchers(antMatcher("/h2-console/**")).permitAll()
                        .anyRequest()
                        .authenticated())
                .httpBasic(withDefaults())
                .csrf(csrf -> csrf.ignoringRequestMatchers(toH2Console()))
                .csrf(httpSecurityCsrfConfigurer -> httpSecurityCsrfConfigurer.disable())
                .addFilterBefore(new ProductFilter(), BasicAuthenticationFilter.class);
        return http.build();

    }
}

我尝试了堆栈溢出中建议的多个选项,但似乎不起作用。

ldfqzlk8

ldfqzlk81#

最简单的方法是为H2控制台公开一个单独的SecurityFilterChain,如下所示:

@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) throws Exception {
    http.securityMatcher(PathRequest.toH2Console());
    http.authorizeHttpRequests(yourCustomAuthorization());
    http.csrf((csrf) -> csrf.disable());
    http.headers((headers) -> headers.frameOptions((frame) -> frame.sameOrigin()));
    return http.build();
}

在参考文档中有关于此的更多信息:https://docs.spring.io/spring-boot/docs/current/reference/html/data.html#data.sql.h2-web-console.spring-security

相关问题