Spring Boot中访问h2-console被重定向至登录页的解决方法
问题描述
我正在学习Spring Boot Security 3.2,创建了一个简单项目并编写了如下SecurityConfig配置类:
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean @Order(1) SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception { return http .securityMatcher("/api/**") .authorizeHttpRequests(auth -> auth .anyRequest() .authenticated()) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .csrf(csrf -> csrf.ignoringRequestMatchers(AntPathRequestMatcher.antMatcher("/h2-console/**"))) .httpBasic(Customizer.withDefaults()) .build(); } @Bean @Order(2) SecurityFilterChain h2ConsoleSecurityFiterChain(HttpSecurity http) throws Exception { return http .securityMatcher("/h2-console/**") .authorizeHttpRequests(auth -> auth .anyRequest().permitAll()) .csrf(csrf -> csrf.ignoringRequestMatchers(AntPathRequestMatcher.antMatcher("/h2-console/**"))) .headers(headers -> headers.frameOptions(FrameOptionsConfig::disable)) .build(); } @Bean @Order(3) SecurityFilterChain secureSecurityFiterChain(HttpSecurity http) throws Exception { return http .authorizeHttpRequests(auth -> { auth.requestMatchers("/").permitAll(); auth.requestMatchers("/error").permitAll(); auth.anyRequest().authenticated(); }) .formLogin(Customizer.withDefaults()) .build(); } }
但尝试访问/h2-console时,页面会重定向到登录表单要求输入用户名和密码,我已使用@Order注解但未生效,请问该如何解决?
解决方案
问题核心在于第三个SecurityFilterChain未设置明确的匹配范围,默认会拦截所有请求,即使你给h2的过滤器链设置了@Order(2),也会被覆盖。具体修正步骤如下:
- 给第三个过滤器链添加明确的
securityMatcher并排除已处理路径
第三个过滤器链没有配置securityMatcher,Spring Security会将其作为默认链,处理所有未被前面链匹配的请求,包括/h2-console。修改后让它仅处理除/api/**和/h2-console/**之外的请求:
@Bean @Order(3) SecurityFilterChain secureSecurityFiterChain(HttpSecurity http) throws Exception { return http .securityMatcher("/**") .authorizeHttpRequests(auth -> { auth.requestMatchers("/", "/error").permitAll(); // 排除已被前两个过滤器链处理的路径 auth.requestMatchers("/api/**", "/h2-console/**").permitAll(); auth.anyRequest().authenticated(); }) .formLogin(Customizer.withDefaults()) .build(); }
- 简化h2控制台的CSRF配置(可选)
针对h2控制台的场景,直接禁用CSRF比忽略匹配更直接,避免路径匹配的潜在问题:
.csrf(csrf -> csrf.disable())
- 确认过滤器链执行逻辑
@Order数值越小优先级越高,你的顺序设置是正确的,但必须保证每个过滤器链都有明确的securityMatcher,否则无匹配规则的链会成为默认兜底链,拦截所有未被匹配的请求,这就是h2控制台被重定向的根本原因。
内容的提问来源于stack exchange,提问作者j virja
相关产品推荐
相关产品推荐

