You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security 6:SecurityFilterChain优先级高于WebSecurityCustomizer的问题咨询

解决Spring Security 6中WebSecurityCustomizer与SecurityFilterChain优先级问题

针对你遇到的/h2-console/**路径仍被jwtRequestFilter拦截的问题,除了直接在过滤器链中配置放行外,还有以下两种可行方案:

方案一:修正WebSecurityCustomizer的路径匹配配置

确保WebSecurity.ignoring()的路径匹配规则准确生效,可显式使用AntPathRequestMatcher声明路径,避免模糊匹配导致的问题:

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
    return (web) -> web.ignoring()
            .requestMatchers(new AntPathRequestMatcher("/h2-console/**"));
}

这种方式会让匹配的请求完全跳过Spring Security的过滤器链,自然不会触发jwtRequestFilter。如果之前配置未生效,大概率是路径匹配规则的隐式转换导致匹配失败,显式指定匹配器可以解决这个问题。

方案二:创建高优先级的独立SecurityFilterChain处理h2-console

通过@Order注解设置一个优先级更高的过滤器链,专门处理/h2-console/**路径,让这类请求不走后续带jwtRequestFilter的过滤器链:

@Bean
@Order(99) // 优先级高于默认的100
SecurityFilterChain h2ConsoleSecurityFilterChain(HttpSecurity http) throws Exception {
    // 仅匹配h2控制台相关路径
    http.securityMatcher("/h2-console/**")
            .csrf(csrf -> csrf.disable()) // h2控制台需要关闭CSRF
            .headers(headers -> headers.frameOptions(frame -> frame.disable())) // 允许iframe访问
            .authorizeHttpRequests(auth -> auth.anyRequest().permitAll());
    return http.build();
}

// 原有的过滤器链保持不变,设置默认优先级100
@Bean
@Order(100)
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.csrf()
            .disable()
            .cors()
            .and()
            .exceptionHandling()
            .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
            .and()
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeHttpRequests(authorize -> authorize
                    .requestMatchers(HttpMethod.OPTIONS).permitAll()
                    .requestMatchers(HttpMethod.GET,"/articles/feed").authenticated()
                    .requestMatchers(HttpMethod.POST, "/users",  "/users/login").permitAll()
                    .requestMatchers(HttpMethod.GET, "/articles/**", "/profiles/**", "/tags").permitAll()
                    .anyRequest().authenticated()
            )
            .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    return http.build();
}

这种方式的优势是可以针对h2控制台单独配置安全规则(比如关闭CSRF、允许iframe),同时不影响原有业务接口的安全逻辑。

内容的提问来源于stack exchange,提问作者Alireza Fattahi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 12:05:33