【问题标题】:How to save the request body after reading it in the ServerAuthenticationConverter?在ServerAuthenticationConverter中读取请求体后如何保存?
【发布时间】:2021-07-14 16:14:31
【问题描述】:

伙计们!也许有人遇到了获取请求正文的问题..

我想成为 Spring WebFlux + Security 的朋友: 我使用安全配置

@EnableWebFluxSecurity
@EnableReactiveMethodSecurity
public class SecurityConfig {
...

我设置的地方

.addFilterAt(authenticationWebFilter(), SecurityWebFiltersOrder.AUTHENTICATION)

用于检查身份验证

    private AuthenticationWebFilter authenticationWebFilter() {
        AuthenticationWebFilter authenticationWebFilter = new AuthenticationWebFilter(new AuthManager());
        authenticationWebFilter.setServerAuthenticationConverter(new AuthDataConverter());
        return authenticationWebFilter;
    }

我有一个自定义转换器 (AuthDataConverter) 和一个自定义管理器 (AuthManager)。 当我执行 POST http 请求时,我陷入了转换器: 在转换器内部 - 我得到请求的标题和正文:

import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authentication.ServerAuthenticationConverter;
import org.springframework.web.server.ServerWebExchange;

public class AuthDataConverter implements ServerAuthenticationConverter {
...
    @Override
    public Mono<Authentication> convert(ServerWebExchange exchange) {
        
        HttpHeaders headers = exchange.getRequest().getHeaders();
        Flux<DataBuffer> body = exchange.getRequest().getBody();
        ...
        Mono<String> m = decodeToString(body);

        return m.map(jsonBody -> {
            Authentication auth = new MyAuthData(headers, jsonBody);
            return auth;
        });
}

一切顺利 - AuthDataConverter 获取请求参数并在 AuthManager 中发送:

import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.core.Authentication;

public class AuthManager implements ReactiveAuthenticationManager {
...
    @Override
    public Mono<Authentication> authenticate(Authentication auth) {
    //check auth object 
    }

}

但是!问题:在下一步中,我陷入了控制器:

@RestController
@RequestMapping("/test")
public class TestController {

    @PostMapping("/addParam")
    public Response<MyParam> addParam(@RequestBody Mono<MyParam> param) {
      //I can't go inside because the request body has already been read in AuthDataConverter
      //How can save body of request?
    }

【问题讨论】:

    标签: java http spring-security controller spring-webflux


    【解决方案1】:

    Reactor HTTP Request Body 订阅一次后,下一次订阅结果为空。这是因为 Reactor 将 HTTP Request Body 的来源设置为 FluxRecive,这是一个动态发布者,将消息体发布为 HTTP Request。因此,当 HTTP Request 消息体被订阅一次时,后续的所有订阅都是空的。因为 HTTP 请求的主体只发送一次。

    这篇文章对我有帮助:https://www.programmersought.com/article/47663615530/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多