【问题标题】:Spring: How to attach SecurityContextHolder on parallel fluxSpring:如何在并行通量上附加 SecurityContextHolder
【发布时间】:2021-05-31 02:57:12
【问题描述】:

我正在使用此代码:

Map<String, ?> result = Flux.range(1, 2)
    .parallel(2)
    .runOn(Schedulers.parallel())
    .map(this::mapWithSecurityContextHolder)
    .sequential()
    .publishOn(Schedulers.single())
    .collect(Collectors.toMap(Pair::getFirst, Pair::getSecond))
    .block();

mapWithSecurityContextHolder 代码是:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Claims claims = (Claims) authentication.getDetails();

所以,authenticationnull,因为通量线程不是请求线程并且引发了 NullPointerException

有什么想法吗?

【问题讨论】:

    标签: spring spring-security spring-webflux


    【解决方案1】:

    您可以(至少)通过 2 种方式来做到这一点,要么使用钩子,要么将其放在反应器上下文中。这基本上是或多或少明确之间的选择。

    (未经测试,伪代码,可能想检查 auth 是否为空等)

    Flux.range...
    .deferWithContext(ctx -> ctx.<Claims>get("claims")...)
    ...
    .subscriberContext(Context.of("claims",SecurityContextHolder.getContext().getAuthentication().getDetails())
    .block()
    

    对于钩子解决方案,我将向您指出this blog post,作者使用钩子来设置/使用 MDC 上下文。我自己从未使用过它,但它也应该可以正常工作

    【讨论】:

      猜你喜欢
      • 2014-01-12
      • 1970-01-01
      • 2011-03-28
      • 2019-09-08
      • 1970-01-01
      • 2021-04-30
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多