23tux
23tux

Reputation: 14736

Cordova: Share webview cookies with native plugins

I have a cordova app, running iOS and Android, which uses cookies for authentication (the user just types in email and password, and the in app browser sets the cookies, backend in Rails with devise). This works so far.

Now I have a native plugin for android and iOS, which uploads some data in background mode (iOS) / as a service (Android). The problem is, that the URL the plugin is trying to access is also protected. So the plugins somehow needs to send the cookies along with the request.

I have found a number of articles, most of them a little bit old (like this one http://blog.winfieldpeterson.com/2013/01/17/cookies-in-hybrid-android-apps), and every solutoin feels like a little bit of overkill.

I'm using Cordova 4.3.0, and maybe there is a standard solution to this, that I haven't found (and got updated since all the other articles were written).

Here is a part of my Android and iOS code, which sends the data to the server:

HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
HttpClient httpclient = new DefaultHttpClient();

SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(httpclient.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, httpclient.getParams());

// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

HttpPost httppost = new HttpPost(locationCache.getUrl());
httppost.setHeader("Content-type", "application/json");

JSONObject body;
body = new JSONObject();
body.put("someKey", "someData");

HttpResponse response = httpclient.execute(httppost);

And the iOS version:

NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:geodata options:0 error:&err];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:url]];
postRequest.HTTPMethod = @"POST";
[postRequest setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
postRequest.HTTPBody = [jsonString dataUsingEncoding: NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:postRequest queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                           if(error) {
                             NSLog(@"Httperror: %@, %d", error.localizedDescription, error.code);
                           } else {
                              NSInteger responseCode = [(NSHTTPURLResponse *)response statusCode];
                              NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                              NSLog(@"REQUEST SENT TO SERVER! HTTP response code: %d; response body: %@", responseCode, responseString);
                           }
                       }];

Hope somedbody can help.

Upvotes: 0

Views: 2022

Answers (1)

jcesarmobile
jcesarmobile

Reputation: 53311

On iOS you can get the cookies for an url like this:

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:@"__YOUR_URL__"]];

or all the cookies like this:

NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];

after that, you can set the request header like this:

NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
[postRequest setAllHTTPHeaderFields:headers]; 

On android you have the webview CookieManager

CookieManager cookieManager=CookieManager.getInstance();
String cookie=cookieManager.getCookie(url);

Upvotes: 1

Related Questions