-
Notifications
You must be signed in to change notification settings - Fork 24.8k
Description
Is this a bug report?
Yes
Have you read the Contributing Guidelines?
Yes
Environment
react-native -v
: react-native-cli: 2.0.1; react-native: 0.46.2node -v
: v8.1.3npm -v
: 5.0.3
-
Target Platform: iOS
-
Development Operating System: macOS 10.12.6
-
Build tools: Xcode
Steps to Reproduce
- Make an HTTP fetch request to an endpoint that performs redirects.
- Inspect the traffic.
- Note that cookies from responses are not included in subsequent HTTP redirected requests.
- Also note that authorization headers (if any) in the original request are not included in subsequent HTTP redirected requests.
Expected Behavior
Expect fetch request to carry cookie and authorization headers over to subsequent HTTP requests when being redirected.
Actual Behavior
Cookies and authorization headers from responses are not carried over into subsequent HTTP requests when being redirected.
Temporary solution
The temporary solution I am using is to edit the React Native source code to intercept each redirect, append the cookie from the last response to the new request, and manually append the authorization header to the new request.
- In XCode, open the YOUR_PROJECT_NAME/ios/projectname.xcworkspace file.
- From the XCode Project Navigator, open projectname/Libraries/RCTNETWORK.xcodeproj/RCTHTTPRequestHandler.mm
- In the file, replace this line:
@interface RCTHTTPRequestHandler () <NSURLSessionDataDelegate>
with this line:
@interface RCTHTTPRequestHandler () <NSURLSessionDataDelegate, NSURLSessionTaskDelegate>
- Finally, after this line:
RCT_EXPORT_MODULE()
insert these lines:
//Modified React Native to manually append the correct cookie to redirected HTTP requests. This carries the cookie through to completion when authenticating.
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler {
NSDictionary *cookiesDict = [NSHTTPCookie requestHeaderFieldsWithCookies: [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies];
NSMutableURLRequest *newRequest = [request mutableCopy];
for (NSString *key in [cookiesDict allKeys]) {
[newRequest setValue: [cookiesDict valueForKey:key] forHTTPHeaderField: key];
}
//Manually append authorization headers
NSString *authStr = [NSString stringWithFormat:@"%@:%@", @“user_name_here”, @“password_here"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]];
[newRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
completionHandler(newRequest);
}
- Save the file.