Spring WebFlux Security如何限制含/admin/的URL访问权限?
Spring WebFlux Security 拦截任意位置含/admin/的路径解决方案
问题原因
- 最初使用的
"**/admin/**"缺少开头的/,属于相对路径匹配,无法覆盖所有含/admin/的URL,导致未正确拦截。 - 改用
"/**/admin/**"时启动报错,是因为Spring WebFlux默认使用PathPatternParser作为路径匹配器,该规则不允许**后面再跟随其他路径元素(如/admin/**)。 spring.mvc.pathmatch.matching-strategy=ant_path_matcher是Spring MVC的配置项,WebFlux环境下完全不生效。
解决方案
方案一:在WebFlux中启用AntPathMatcher匹配路径
WebFlux支持手动指定使用AntPathMatcher来处理复杂路径匹配,具体步骤如下:
- 定义AntPathMatcher的Bean:
@Bean public AntPathMatcher antPathMatcher() { return new AntPathMatcher(); }
- 在Security配置中,使用
ServerWebExchangeMatchers.pathMatchers指定用AntPathMatcher匹配"/**/admin/**"路径:
修改后的完整配置:
@EnableWebFluxSecurity public class SpringSecurityConfig { @Autowired private JwtAuthenticationFilter authenticationFilter; @Autowired private ReactiveAuthenticationManager authenticationManager; @Bean public AntPathMatcher antPathMatcher() { return new AntPathMatcher(); } @Bean public SecurityWebFilterChain configure(ServerHttpSecurity http, AntPathMatcher antPathMatcher) { return http .cors() .configurationSource(request -> { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("http://127.0.0.1:8080")); configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); configuration.setAllowedHeaders(Arrays.asList("Authorization", "Content-Type")); return configuration; }) .and() .csrf().disable() .authorizeExchange() .pathMatchers("/authentication/**").permitAll() // 使用AntPathMatcher匹配任意位置包含/admin/的URL .matchers(ServerWebExchangeMatchers.pathMatchers(antPathMatcher, "/**/admin/**")).hasRole("SUPERVISOR") .anyExchange().authenticated() .and() .addFilterAt(authenticationFilter, SecurityWebFiltersOrder.AUTHENTICATION) .build(); } }
方案二:检查角色权限前缀(关键排查点)
如果配置后仍未生效,需确认角色权限的前缀问题:
hasRole("SUPERVISOR")会自动为角色添加ROLE_前缀,即实际检查的是ROLE_SUPERVISOR权限。- 如果你的用户角色是
SUPERVISOR(无ROLE_前缀),请改用hasAuthority("SUPERVISOR")替代hasRole。
内容的提问来源于stack exchange,提问作者Yadier Betancourt Martínez
相关产品推荐
相关产品推荐

