Spring Security Filter Chain请求匹配失效,如何保护指定端点?
Spring Security 路径权限规则覆盖解决方案
Spring Security的授权规则是按声明顺序匹配的——先匹配到的规则会直接生效,后续规则不会再执行。你之前的配置先声明了.requestMatchers("/api/v1/auth/**").permitAll(),这个通配符会覆盖所有/api/v1/auth/下的路径(包括validate-session),导致后面的认证规则根本不会被触发。
解决方法
把更具体的路径规则放在前面,先定义/api/v1/auth/validate-session的认证要求,再声明/api/v1/auth/**允许匿名访问。这样具体路径会优先匹配,剩下的Auth下其他路径才会走允许匿名的规则。
修改后的完整配置代码:
http .csrf(AbstractHttpConfigurer::disable) .cors(customizer -> customizer .configurationSource(request -> { CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Collections.singletonList("http://localhost:3000")); config.setAllowedMethods(Collections.singletonList("*")); config.setAllowedHeaders(Collections.singletonList("*")); config.setAllowCredentials(true); config.setMaxAge(3600L); return config; })) .authorizeHttpRequests(customizer -> customizer // 先声明具体路径的认证要求 .requestMatchers("/api/v1/auth/validate-session").authenticated() // 再声明auth下其余路径允许匿名访问 .requestMatchers("/api/v1/auth/**").permitAll() .requestMatchers("/api/v1/demo").authenticated() .anyRequest().authenticated() ) .sessionManagement(customizer -> customizer .invalidSessionUrl("/api/v1/auth/logout?expired") .maximumSessions(1) .maxSessionsPreventsLogin(false) ) .httpBasic(Customizer.withDefaults()) .logout(customizer -> customizer .logoutUrl(LOGOUT_URL) .logoutSuccessUrl(LOGOUT_SUCCESS_URL) .invalidateHttpSession(true) .deleteCookies("JSESSIONID") ); return http.build();
关键注意点
- 规则顺序是核心:越具体的路径规则,越要放在前面;通配符范围大的规则必须后置。
- 如果有多个类似的特殊路径,都要遵循这个逻辑,把每个具体路径的规则放在对应通配符规则之前。
内容的提问来源于stack exchange,提问作者Meriç Bulca
相关产品推荐
相关产品推荐

