【问题标题】:null principal returned by ServerRequest in webflux request handlerWebflux 请求处理程序中 ServerRequest 返回的 null 主体
【发布时间】:2023-03-10 17:53:01
【问题描述】:

我已经在 Spring WebFlux 应用程序中设置了身份验证。身份验证机制似乎工作正常。例如下面的代码用于设置安全网络过滤链:

@Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {

    return http.authorizeExchange()
            .pathMatchers("/path/to/resource").hasAuthority("A_ROLE")
            .anyExchange().authenticated()
            .and().httpBasic()
            .and().build();
}

这可以与 UserDetailsRepositoryReactiveAuthenticationManager 和 MapReactiveUserDetailsS​​ervice 一起按预期工作。如果用户没有所需的权限,则返回禁止的错误代码,否则将请求传递给处理程序。

我需要在处理程序本身内应用细粒度的权限检查,并认为我应该能够从请求中检索权限,如下所示:

public Mono<ServerResponse> getMyResource(ServerRequest serverRequest) {

      Authentication authentication = (Authentication)serverRequest.principal().block();
      ...   
}

但是,我发现本金始终为空。首先,这是处理当局的正确方法吗?如果是,我可能缺少一些上游配置吗?

【问题讨论】:

    标签: spring-security spring-webflux


    【解决方案1】:

    您在可用之前阻止了结果。您可以简单地对其进行平面映射,这样您就不必阻止它。

    public Mono<ServerResponse> getMyResource(ServerRequest serverRequest) {
        return serverRequest.principal().flatMap((principal) -> ServerResponse.ok()
                .body(fromObject("Hello " + principal.getName())));
    }
    

    更新:如果你想检索主体和正文,你可以压缩它们。

    public Mono<ServerResponse> getMyResource(ServerRequest serverRequest) {
        return Mono.zip(
                serverRequest.principal(),
                serverRequest.bodyToMono(String.class)
        ).flatMap(tuple -> {
            Principal principal = tuple.getT1();
            String body = tuple.getT2();
            return ServerResponse.ok().build();
        });
    }
    

    【讨论】:

    • 请告诉我,如果我想要工作witk登录和正文对象,请告诉我如何从请求中检索principal.getName() 和之后的bodyToMono?;
    猜你喜欢
    • 2015-02-12
    • 2012-02-26
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    • 2018-07-29
    • 2021-03-03
    • 2018-10-31
    • 2021-01-28
    相关资源
    最近更新 更多