简体   繁体   中英

How can i add multiple user roles to single pathMatcher/Route in Spring WebFlux Security(Reactive Spring Security) Config?

i have a route that needs to authenticated for more than one user. performing integration testing on spring cloud gateway service to test all the routes security working as expected or not. how can i add more than 1 user role to single pathMatcher/route?

Using Spring Boot 2.1.6, Spring Cloud Finchely.SR2, Spring Cloud Gateway, Spring WebFlux Security(Reactive Spring Security)

@EnableWebFluxSecurity
public class SecurityConfig {

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {

http.csrf().disable()        
           .formLogin().disable()
           .logout().disable()
           .authorizeExchange()
           .pathMatchers(prefix + "/publish/**")
           .hasRole("XYZ_ROLE") //Here i want to add more than one user role
           .anyExchange()
           .authenticated().and().httpBasic();
        }
}

EDIT:

After looking through the spring security source code and github issues i found out that hasAnyRole and hasAnyAuthority has been implemented for spring security for webflux and is planned to be released in Spring security v5.2.0 .

As of writing current stable version is 5.1.6 but the 5.2.0 is in milestone 4 so it should be released very soon. You can use the snapshot version of 5.2.0 if needed.

The only other current option if not using the snapshot is to implement your own custom ReactiveAuthorizationManager and use the ServerHttpSecurity.AuthorizeExchangeSpec#access function.

OLD ANSWER ONLY APPLICABLE TO STANDARD SPRING SECURITY NOT WEBFLUX:

You can try out the hasAnyRole(String... roles)

after digging the rabbit hole, i found solution to Authorize for multiple roles using Reactive Spring Security. find the solution below:

public class SecurityConfig {

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {

http.csrf().disable()        
           .formLogin().disable()
           .logout().disable()
           .authorizeExchange()
                     .pathMatchers(prefix + "/publish/**").access((mono, context) -> mono
                                            .map(auth -> auth.getAuthorities().stream()

//Authorizing for multiple user roles                       
.filter(e -> (e.getAuthority().equals("ROLE_ABC") || e.getAuthority().equals("ROLE_XYZ"))) 
                                            .count() > 0)
                                            .map(AuthorizationDecision::new))

           .anyExchange()
           .authenticated().and().httpBasic();
        }
}```


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM