我使用Spring Security和Spring Cloud Gateway,需要配置需要多个权限的路由。到目前为止,我只能为每条路由指定一个单独的权限:
@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")
.anyExchange().authenticated())
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(grantedAuthoritiesExtractor())));
return http.build();
}
我如何扩展这一点,使某些路由需要多个授权?如:
.pathMatchers("/api/example/**/).hasAuthority("Developer").hasAuthority("SeniorDev")
.hasAnyAuthority("Developer", "SeniorDev")
方法存在并作为OR语句工作,但我没有看到用于and语句的方法。
你可以使用下面的代码:
.antMatchers("/api/example/**").access("hasAuthority('developer') and hasAuthority('admin')")
**********
为ServerHttpSecurity尝试此解决方案
.pathMatchers("/api/example/**").access((mono, context) -> mono
.map(auth -> auth.getAuthorities().stream()
.filter(e -> (e.getAuthority().equals("ADMIN") && e.getAuthority().equals("DEVELOPER"))).count() > 0)
.map(AuthorizationDecision::new))