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

Spring Security按路径配置公共访问、JWT与HTTP Basic认证问题求助

问题分析与修正方案

原有配置存在4个核心问题导致无法匹配需求:

  • 未配置全局默认拒绝策略,无匹配规则的端点不会自动返回禁止访问
  • JWT过滤器全局生效,会拦截/api/**路径的请求,干扰HTTP Basic认证流程
  • 权限规则顺序混乱,且没有明确保证白名单优先级最高
  • 缺失API_USER_ROLE常量定义,重复配置会话管理策略

修正后完整代码

@Configuration
@RequiredArgsConstructor
public static class ApiSecurityConfiguration extends WebSecurityConfigurerAdapter {

    private static final String API_USER_ROLE = "api-role";
    private static final String[] RESOURCE_WHITELIST = {
            "/services/login",
            "/services/reset-password",         
            "/metrics",
            "/api/notification"
    };

    private final JwtRequestFilter jwtRequestFilter;

    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

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

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("some-username")
                .password(passwordEncoder().encode("some-api-password"))
                .roles(API_USER_ROLE);
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .cors()
                .and()
                .csrf().disable()
                .formLogin().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests()
                // 白名单优先级最高,直接放行
                .mvcMatchers(RESOURCE_WHITELIST).permitAll()
                // /api/**路径走HTTP Basic认证
                .mvcMatchers("/api/**").hasRole(API_USER_ROLE)
                // /services/**走JWT认证
                .mvcMatchers("/services/**").authenticated()
                // 所有未匹配路径默认拒绝访问
                .anyRequest().denyAll()
                .and()
                .httpBasic();
    }
}

额外需要调整的JWT过滤器逻辑

需要在JwtRequestFilter的doFilterInternal方法开头增加路径判断,避免对非/services/**路径执行JWT校验:

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    // 新增路径判断:非/services/**路径或白名单路径直接跳过JWT校验
    String path = request.getRequestURI();
    if (!path.startsWith("/services/") || Arrays.stream(RESOURCE_WHITELIST).anyMatch(path::equals)) {
        filterChain.doFilter(request, response);
        return;
    }
    // 原有JWT校验逻辑保留
    // ...
}

配置校验规则说明

权限匹配按声明顺序从上到下执行:

  1. 优先匹配白名单路径,匹配到直接放行,无需任何认证
  2. 匹配/api/**路径,校验HTTP Basic认证信息及角色权限
  3. 匹配/services/**路径,校验JWT令牌有效性
  4. 所有未匹配到以上规则的请求,直接返回403禁止访问

内容的提问来源于stack exchange,提问作者Robert Strauch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:45:04