From a6860487947ae0957f5dfa4979e92bc7740fecb0 Mon Sep 17 00:00:00 2001 From: Olivier Corradi Date: Sun, 25 Nov 2018 22:58:02 -0800 Subject: [PATCH] Fix cookies not being sent after a redirected response (#22178) Summary: Fixes https://github.com/facebook/react-native/issues/19376 On iOS, the `HTTPShouldHandleCookies` boolean has no effect when custom cookies are set (see https://developer.apple.com/documentation/foundation/nsmutableurlrequest/1415485-httpshouldhandlecookies?preferredLanguage=occ). Setting custom cookies prevents the cookies of a redirect response from being re-used in the subsequent request. This is why issue https://github.com/facebook/react-native/issues/19376 is opened. The fix is to intercept the redirect request, and to manually set the cookies. This effectively makes the Android and iOS behaviours converge. Changelog: ---------- [iOS] [Fixed] - Fix cookies not being sent on iOS after redirect Pull Request resolved: https://github.com/facebook/react-native/pull/22178 Differential Revision: D13191961 Pulled By: shergin fbshipit-source-id: 4445a2499034a9846c6d7c37c1f1b72c9fd30129 --- Libraries/Network/RCTHTTPRequestHandler.mm | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Libraries/Network/RCTHTTPRequestHandler.mm b/Libraries/Network/RCTHTTPRequestHandler.mm index 4d922f52d0c..863fea857dd 100644 --- a/Libraries/Network/RCTHTTPRequestHandler.mm +++ b/Libraries/Network/RCTHTTPRequestHandler.mm @@ -108,6 +108,21 @@ totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend [delegate URLRequest:task didSendDataWithProgress:totalBytesSent]; } +- (void)URLSession:(NSURLSession *)session + task:(NSURLSessionTask *)task +willPerformHTTPRedirection:(NSHTTPURLResponse *)response + newRequest:(NSURLRequest *)request + completionHandler:(void (^)(NSURLRequest *))completionHandler +{ + // Reset the cookies on redirect. + // This is necessary because we're not letting iOS handle cookies by itself + NSMutableURLRequest *nextRequest = [request mutableCopy]; + + NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL]; + nextRequest.allHTTPHeaderFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; + completionHandler(nextRequest); +} + - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)task didReceiveResponse:(NSURLResponse *)response