小编Jul*_*3nT的帖子

ReactiveSecurityContextHolder 在 Spring WebFlux 中为空

我正在尝试将 ReactiveSecurityContextHolder 与 Spring WebFlux 一起使用。不幸的是, SecurityContext 是空的:

@Configuration
public class Router {

    @Bean
    public RouterFunction<ServerResponse> routes(Handler handler) {
        return nest(
                path("/bill"),
                route(
                        GET("/").and(accept(APPLICATION_JSON)), handler::all));
    }

    @Component
    class Handler {

        Mono<ServerResponse> all(ServerRequest request) {

            ReactiveSecurityContextHolder.getContext()
                .switchIfEmpty(Mono.error(new IllegalStateException("ReactiveSecurityContext is empty")))
                .map(SecurityContext::getAuthentication)
                .map(Authentication::getName)
                .flatMap(s -> Mono.just("Hi " + s))
                .subscribe(
                        System.out::println,
                        Throwable::printStackTrace,
                        () -> System.out.println("completed without a value")
                );

            return ok().build();
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

此代码始终抛出 IllegalStateException。

如果我添加一个subscriberContext像显示在这里

Authentication authentication = new TestingAuthenticationToken("admin", "password", "ROLE_ADMIN");

ReactiveSecurityContextHolder.getContext()
        .switchIfEmpty(Mono.error(new IllegalStateException("ReactiveSecurityContext is empty")))
        .map(SecurityContext::getAuthentication) …
Run Code Online (Sandbox Code Playgroud)

spring spring-security spring-boot reactive spring-webflux

6
推荐指数
1
解决办法
6519
查看次数