Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enable cookie persistence with Spring WebClient

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?

like image 504
Villa de Espinos Avatar asked Mar 09 '26 09:03

Villa de Espinos


1 Answers

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
    }
}
like image 195
Archimedes Trajano Avatar answered Mar 10 '26 23:03

Archimedes Trajano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!