I need to test a login flow with Spring's reactive WebClient. My login flow sets cookies during a series of redirects which makes it cumbersome to track the cookies manually. Does WebClient or any of its connectors have support for cookies? I've created an ExchangeFilterFunction using Java's java.net.CookieManager, but it's still not behaving the same way as RestTemplate configured with cookie support through the Apache HttpClient. Is there a better way, other writing my own cookie persistence?
I had to write one for my tests
class CookieManager : ExchangeFilterFunction {
private val cookies: MutableMap<String, ResponseCookie> = HashMap()
override fun filter(request: ClientRequest, next: ExchangeFunction): Mono<ClientResponse> =
next.exchange(withClientCookies(request)).doOnSuccess { response: ClientResponse ->
response.cookies().values.forEach { cookies ->
cookies.forEach {
if (it.maxAge.isZero) {
this.cookies.remove(it.name)
} else {
this.cookies[it.name] = it
}
}
}
}
private fun withClientCookies(request: ClientRequest): ClientRequest =
ClientRequest.from(request).cookies { it.addAll(clientCookies()) }.build()
private fun clientCookies(): MultiValueMap<String, String> {
val result: MultiValueMap<String, String> = LinkedMultiValueMap(cookies.size)
cookies.values.forEach {
result.add(
it.name,
it.value
)
}
return result
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With