0

我正在尝试使用 WebClient 连接到具有 CSRF 保护的 API。如何ExchangeFilterFunction处理XSRF-TOKENcookie 和包含X-XSRF-TOKEN标头?

4

1 回答 1

0

这就是我想出的解决方案:

public class CsrfClientExchangeFilterFunction implements ExchangeFilterFunction
{
    @Override
    public Mono<ClientResponse> filter( ClientRequest request, ExchangeFunction next)   {
        return next.exchange( request )
            .flatMap( response -> {
                if( response.statusCode().is4xxClientError() )
                {
                    ResponseCookie csrfCookie = response.cookies().getFirst( "XSRF-TOKEN" );
                    if( csrfCookie != null )
                    {
                        ClientRequest retryRequest = ClientRequest.from( request )
                                .headers( httpHeaders -> httpHeaders.set( "X-XSRF-TOKEN", csrfCookie.getValue() ) )
                                .cookies( cookies -> cookies.add(  "XSRF-TOKEN", csrfCookie.getValue() ) )
                                .build();

                        return next.exchange( retryRequest );
                    }
                }
                return Mono.just( response );
            } );
    }
}

作为参考,如果ClientRequest.Builder#cookie(String name, String... values)使用代替ClientRequest.Builder#cookies(Consumer<MultiValueMap<String, String>> cookiesConsumer). 我很想知道为什么!

编辑:

Spring Framework 项目的不同行为ClientRequest.Builder#cookiesClientRequest.Builder#cookie方法已被报告为问题 - 您可以在此处找到它

于 2019-08-22T14:00:41.413 回答