我正在尝试使用WebClient连接到具有CSRF保护的API。 ExchangeFilterFunction
看起来如何处理XSRF-TOKEN
cookie并包含X-XSRF-TOKEN
标头?
答案 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#cookies
和ClientRequest.Builder#cookie
方法的不同行为是Spring Framework项目的一个问题-您可以here找到它