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

Spring Security未拦截指定URL:仅允许特定URL却放行全部

问题原因分析

你的配置之所以出现两个URL都能访问的情况,核心问题出在**requestMatcher的错误使用方式**以及Spring Security的过滤器链匹配逻辑:

  1. requestMatcher的覆盖特性:
    在同一个HttpSecurity实例中多次调用requestMatcher,后续调用会直接覆盖之前设置的匹配规则。你的代码里最后一次调用requestMatcher(new AntPathRequestMatcher("/OtherHandlerServices/Test")),会让整个过滤器链只对/OtherHandlerServices/Test请求生效,/RemoteHandlerServices/Handle请求完全不会被这个链匹配到。

  2. 未匹配请求的默认放行逻辑:
    Spring Security对没有被任何SecurityFilterChain匹配到的请求,会默认直接放行,不做任何安全校验。这就导致/RemoteHandlerServices/Handle因为没被过滤器链覆盖,所以可以直接访问。

  3. /OtherHandlerServices/Test的规则失效:
    虽然你给该URL配置了denyAll(),但由于过滤器链的匹配范围被错误限定,再加上如果没有配套的认证机制(比如未配置登录、Token校验等),最终导致这条拒绝规则没有被正确触发,请求依然能被放行。

正确配置示例

要实现「仅允许访问/RemoteHandlerServices/Handle,拒绝其他所有URL」的需求,不需要多次调用requestMatcher,只需在同一个authorizeHttpRequests块中按优先级配置规则即可:

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    try {
        return http
                .authorizeHttpRequests(auth -> auth
                        // 指定该URL需要认证后访问
                        .antMatchers("/RemoteHandlerServices/Handle").authenticated()
                        // 所有其他请求一律拒绝
                        .anyRequest().denyAll()
                )
                .build();
    } catch (Exception e) {
        throw new RuntimeException("Authentication configuration failed", e);
    }
}

注意:如果要让/RemoteHandlerServices/Handle的认证规则生效,你还需要补充对应的认证配置(比如添加formLogin()、httpBasic()或自定义认证过滤器),否则未认证的请求访问该URL会被Spring Security拦截并返回401/403。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 08:55:26