Spring Cloud Gateway中Spring Security多权限(AND)路由配置
实现Spring Cloud Gateway路由的多权限逻辑与校验
要实现路由需要同时拥有多个权限才能访问的逻辑与校验,你可以通过以下两种可靠方式配置:
方法1:使用SpEL表达式(简单场景首选)
利用access()方法结合Spring Security的SpEL表达式,直接通过and关键字指定多个权限的逻辑与关系:
@Order(Ordered.HIGHEST_PRECEDENCE) @Bean public SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) { http.securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**")) .authorizeExchange(exchanges -> exchanges .pathMatchers("/api/developer/**").hasAuthority("Developer") .pathMatchers("/api/admin/**").hasAuthority("Admin") // 要求同时拥有Developer和SeniorDev权限 .pathMatchers("/api/example/**").access("hasAuthority('Developer') and hasAuthority('SeniorDev')") .anyExchange().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(grantedAuthoritiesExtractor()))); return http.build(); }
这种方式无需额外代码,直接通过表达式实现多权限的与校验,适合简单的固定权限组合场景。
方法2:自定义ReactiveAuthorizationManager(复杂场景)
如果需要更灵活的权限校验逻辑(比如动态获取权限、添加额外判断条件),可以自定义权限管理器:
步骤1:实现ReactiveAuthorizationManager
public class CompositeAndAuthorityManager implements ReactiveAuthorizationManager<AuthorizationContext> { private final List<String> requiredAuthorities; public CompositeAndAuthorityManager(List<String> requiredAuthorities) { this.requiredAuthorities = requiredAuthorities; } @Override public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext context) { return authentication .filter(Authentication::isAuthenticated) .map(auth -> { // 校验用户是否拥有所有指定权限 boolean hasAll = requiredAuthorities.stream() .allMatch(required -> auth.getAuthorities().stream() .anyMatch(granted -> granted.getAuthority().equals(required))); return new AuthorizationDecision(hasAll); }) .defaultIfEmpty(new AuthorizationDecision(false)); } }
步骤2:在配置中使用自定义管理器
@Order(Ordered.HIGHEST_PRECEDENCE) @Bean public SecurityWebFilterChain apiHttpSecurity(ServerHttpSecurity http) { http.securityMatcher(new PathPatternParserServerWebExchangeMatcher("/api/**")) .authorizeExchange(exchanges -> exchanges .pathMatchers("/api/developer/**").hasAuthority("Developer") .pathMatchers("/api/admin/**").hasAuthority("Admin") // 传入需要同时拥有的权限列表 .pathMatchers("/api/example/**").access(new CompositeAndAuthorityManager(Arrays.asList("Developer", "SeniorDev"))) .anyExchange().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(grantedAuthoritiesExtractor()))); return http.build(); }
注意事项
部分旧版本的Spring Security WebFlux中,链式调用多个hasAuthority()可能会覆盖之前的配置而非叠加校验条件,因此不推荐依赖这种方式实现逻辑与,优先使用上述两种方法确保校验逻辑生效。
内容的提问来源于stack exchange,提问作者David Beaudway
相关产品推荐
相关产品推荐

