laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Http client share cookies between requests #2479

Closed yoramdelangen closed 3 years ago

yoramdelangen commented 3 years ago

I ran in a situation that I use all cookies from previous requests within a new call. Think of login session sharing between the requests. Currently you have to do something like:

// login request
$req = Http::post('url-to-login', $data);
// Guzzle's CookieJar instance, map it to [key=>value]
// yep single line (not tested)
$cookies = collect($req->cookies->toArray())->keyBy('Name')->map->Value; 

$req2 = Http::withCookies($cookies, 'domain')->get('some-behind-login');
$req3 = Http::withCookies($cookies, 'domain')->get('another-url-that-requires-session');

etc and its can be tedious do repeat the process over and over (for example within tests). There is also the problem that cookies can be set on multiple domains, thats not even possible (due to withCookies method sets an 'cookies' option param and it will be overwritten each time the method is called). By using the CookieJar class it would enable it to use multiple domain cookies.

Proposal to add a withCookieJar method that accepts and instance of Guzzle's CookieJar, FileCookieJar or SessionCookieJar class. I'd like to implemented this, but what would be the best approach for this. I have 2 suggestions in mind:

// set CookieJar on local instance
$cookieJar = new CookieJar();

Http::withCookieJar($cookieJar)->post('login-url', $data);

$req2 = Http::withCookieJar($cookieJar)->get('some-behind-login');
$req3 = Http::withCookieJar($cookieJar)->get('another-url-that-requires-session');

or only define it once and create a "static" instance on the PendingRequests class:

// defines a new cookieJar instance in a static property
Http::useCookieJar()->post('login-url', $data);
// or usage for FileCookieJar
Http::useFileCookieJar('filename to store session')->post('login-url', $data);

$req2 = Http::get('some-behind-login');
$req3 = Http::get('another-url-that-requires-session');

Or combining the 2 scenario's can be an option.

Of course the name convention of this can be optimised.. hopefully you'll get the gist.

themsaid commented 3 years ago

Feel free to open a PR with your proposed changes.