WebClient-处理XSRF / CSRF令牌

时间:2019-08-22 13:56:41

标签: spring spring-webclient

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

1 个答案:

答案 0 :(得分: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),则无效。我很想知道为什么!

编辑:

已报告ClientRequest.Builder#cookiesClientRequest.Builder#cookie方法的不同行为是Spring Framework项目的一个问题-您可以here找到它