tmenier / Flurl

Fluent URL builder and testable HTTP client for .NET
https://flurl.dev
MIT License
4.23k stars 387 forks source link

Flurl CookieJar backup and restore #758

Closed Pureaznangel closed 11 months ago

Pureaznangel commented 1 year ago

Please describe the feature/enhancement in as much detail as possible.

Hello Tmenier and Everyone,

Is there any way or method that support me to export (backup) and import (restore) CookieJar for later use?

Thanks,

tmenier commented 1 year ago

You could serialize the data manually however you choose and re-hydrate a CookieJar using AddOrReplace. But I would concede that this would be easier if not for the FlurlCookie constructor and read-only properties that make it impossible to, for example, just JSON-serialize/deserialize the whole thing in one shot. I'll keep this open as a possible 4.0 enhancement.

lisongkun commented 1 year ago
return Cookie.Count == 0 ? string.Empty : string.Join("; ", Cookie.Select(cookie => $"{cookie.Name}={cookie.Value}"));
tmenier commented 1 year ago

Good news! CookieJar persistence will land in 4.0 as a first-class feature. Here's how it'll work:

// string-based usage pattern
var saved = jar.ToString();
var jar2 = CookieJar.LoadFromString(saved);

// TextWriter-based usage pattern (i.e. save to a file)
using var writer = new StreamWriter("path/to/file");
jar.WriteTo(writer);

using var reader = new StreamReader("path/to/file");
var jar2 = CookieJar.LoadFrom(reader);

For both usage patterns, the text-based representation is simple and human-readable. It contains 3 lines for each cookie, representing the 3 pieces of information needed to fully hydrate a FlurlCookie: the date it was received, the URL from which it originated, and all details received in the Set-Cookie header.

2023-09-19T20:30:08
https://mydomain.com/endpoint
x=foo; Domain=mydomain.com; Secure; HttpOnly
...

BREAKING: A few public utility methods on CookieCutter have changed, though calling these methods directly from application code is not likely very common.

pinkplus commented 1 year ago

@tmenier Thanks for adding the new persistence methods. This is much better than before.

I wonder if it's possible to make use of it with the CookieSession class as well. Now CookieSession initializes its own CookieJar instance. On the other hand, the static LoadFrom method on CookieJar always creates a new instance. As a result, loaded cookie jars can't be used in CookieSession.

What about making the LoadFrom method an instance method instead of a static method? The cookies in the input will override the current values in the jar.

tmenier commented 1 year ago

@pinkplus Thanks for pointing this out, I think I overlooked CookieSession when I did this enhancement. Could you open a new issue though? I 'd like to track it separately in case it doesn't make it out in the initial 4.0 release. Thanks.

pinkplus commented 1 year ago

Sure, created #775.