Luca3317 / OpenLibrary.NET

C# library for OpenLibrary by the InternetArchive
MIT License
15 stars 3 forks source link

session cookie issue on iOS #15

Closed bradyguyc closed 1 week ago

bradyguyc commented 1 month ago

I have been using the OpenLibrary.NET with a .NET Maui app and testing on android for quite some time now. I tested on iOS today and discovered a problem related to session cookies. It appears that when running on iOS th session cookie has a discard tag on it and is not available in the normal manner.

I pulled the source code down and created a work around. In openlibraryclient.cs

I added a property sessionCookie and changed the LoggedIn property as follows.


 string sessionCookie = null;
 public bool LoggedIn => !string.IsNullOrWhiteSpace(sessionCookie);

In the LoginAsycn method I added two lines of code after the response.Ensure... line;

 var response = await _httpClient.PostAsync(uri, content);
 response.EnsureSuccessStatusCode();

   string s = response.ToString();
   sessionCookie = Regex.Match(s, "(?<=session=).*?(?=;)").Value;   

And updated Username as follows ` public string? Username => ExtractUsernameFromSessionVariable(sessionCookie);

private static string ExtractUsernameFromSessionVariable(string sessionCookie) => Regex.Match(sessionCookie, "(?<=/people/).*?(?=%)").Value; ` I doubt this is the best way to handle this but the work around seems to be working and the API's are working as expected.

copilot hinted at NSHttpCookieStorage, as a possible solution but that would require bringing in >NET Maui packages into OpenLibrary.NET and that didn't seem like a good idea. Which lead me to iOS binary cookies and I spent a little looking at the package NetBinaryCookie but could not get it to work. And not sure it would be any better than the workaround.

At this point I am having to use the replicated code base in my app so that it works on iOS. I'll keep testing and let you know if anything else enlighting comes about.

Thanks

bradyguyc commented 1 month ago

So what worked with iOS did not work with android. updated it as follows

string s = response.ToString(); sessionCookie = Regex.Match(s, "(?<=session=).*?(?=;)").Value; if(string.IsNullOrWhiteSpace(sessionCookie)) { sessionCookie = _httpHandler.CookieContainer.GetCookies(OpenLibraryUtility.BaseUri).SingleOrDefault(cookie => cookie.Name == "session").ToString(); Debug.WriteLine("sessionCookie android:" + sessionCookie);

basically first check the result for cookie with regex before the cookie gets discarded. if it's blank then use the orginal method to get the cookie.

bradyguyc commented 1 week ago

This is resolved with out code change when I recompiled openlibrary.net with .net 9.0; My maui app that I am using this with is in a .net 9 environment. So all that muck above is not needed once I recompiled and changed the .net version to 9.0;