java—如何在serverauthenticationconverter中读取请求正文后保存它?

ws51t4hk  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(595)

伙计们!也许有人面临着获取请求主体的问题。。
我正在尝试将springwebflux+security作为朋友:我使用securityconfig

@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)。当我发布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?
    }
a0zr77ik

a0zr77ik1#

订阅一次http请求主体后,下一次订阅的结果为空。这是因为reactor将http请求主体的源设置为fluxrecive,fluxrecive是一个将消息主体发布为http请求的动态发布服务器。因此,当http请求消息体被订阅一次时,所有后续订阅都是空的。因为http请求的主体只发送一次。
对我来说,这篇文章:https://www.programmersought.com/article/47663615530/

相关问题