From debcac59d06d527c3a6a07ef9561fe4041022ff4 Mon Sep 17 00:00:00 2001 From: Jelle van den Hooff Date: Mon, 1 Feb 2016 14:18:26 -0800 Subject: [PATCH] iOS websocket: include cookies with request Summary: This PR modifies the Websocket implementation on iOS to pass cookies to the server. Sending cookies is useful for clients that wish to access protected Websocket endpoints without creating a new authentication protocol. Closes https://github.com/facebook/react-native/pull/5630 Reviewed By: svcscm Differential Revision: D2881815 Pulled By: martinbigio fb-gh-sync-id: 31c1640626cd15447bdb4f2058ae4e34dfa52f88 --- Libraries/WebSocket/RCTSRWebSocket.m | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/Libraries/WebSocket/RCTSRWebSocket.m b/Libraries/WebSocket/RCTSRWebSocket.m index 3d8782c87..bf67c3b14 100644 --- a/Libraries/WebSocket/RCTSRWebSocket.m +++ b/Libraries/WebSocket/RCTSRWebSocket.m @@ -280,7 +280,23 @@ RCT_NOT_IMPLEMENTED(- (instancetype)init) - (instancetype)initWithURL:(NSURL *)URL protocols:(NSArray *)protocols options:(NSDictionary *)options { - NSURLRequest *request = URL ? [NSURLRequest requestWithURL:URL] : nil; + NSMutableURLRequest *request; + if (URL) { + // Build a mutable request so we can fill the cookie header. + request = [NSMutableURLRequest requestWithURL:URL]; + + // We load cookies from sharedHTTPCookieStorage (shared with XHR and + // fetch). To get HTTPS-only cookies for wss URLs, replace wss with https + // in the URL. + NSURLComponents *components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:true]; + if ([components.scheme isEqualToString:@"wss"]) { + components.scheme = @"https"; + } + + // Load and set the cookie header. + NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:components.URL]; + [request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:cookies]]; + } return [self initWithURLRequest:request protocols:protocols options:options]; }