来自 ReactiveSecurityContext 的 Spring WebClient 标头

Posted

技术标签:

【中文标题】来自 ReactiveSecurityContext 的 Spring WebClient 标头【英文标题】:Spring WebClient header from ReactiveSecurityContext 【发布时间】:2021-06-10 15:57:26 【问题描述】:

我正在尝试根据经过身份验证的用户设置 WebClient 标头值,如下所示:

webClient.post().header(HttpHeaders.AUTHORIZATION, getUserIdFromSession())...

public String getUserIdFromSession() 
  Mono<Authentication> authentication = ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication);

  //do something here to get user credentials and return them


我应该将所需的标头值存储在其他地方吗?因为以反应方式,一切都返回一个 Mono/Flux 并且我目前无法使用经过身份验证的用户数据,因为我已将其与 Spring MVC 一起使用。在那里我可以做SecurityContextHolder.getContext().getAuthentication()

【问题讨论】:

【参考方案1】:

您是否有理由不只是对身份验证进行平面映射然后调用网络客户端?您也可以从您的方法中返回 Mono&lt;String&gt;

ReactiveSecurityContextHolder.getContext().map(SecurityContext::getAuthentication)
.flatMap(auth -> webClient.post().header(HttpHeaders.AUTHORIZATION, auth.getUserId()).exchange();

【讨论】:

不知道这种方法,效果很好,谢谢!

以上是关于来自 ReactiveSecurityContext 的 Spring WebClient 标头的主要内容,如果未能解决你的问题,请参考以下文章