Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling cookies in PhoneGap/Cordova

I'm working on a PhoneGap app with server session usage. It needs cookies to handle the session. Additionally, the cookie from the load balancer should be handled, too. So there is no way around. How do you handle Cookies in your PhoneGap app?

I have already accomplished some research:

  • Some say cookie handling might depend on the server not setting cookies for unknown user agents (IIS): PhoneGap session (cookies) on iOS
  • In JavaScript cookies can be set with document.cookie = ..., but they are not saved in PhoneGap and lost. Before firing xhr requests it works.
  • Cookies can be retrieved after xhr request with xhr.getResponseHeader('Set-Cookie'). But only when actually set on the server. Unfortunately, jQuery strips the "Cookie" header.
  • The JavaScript document.cookie property is not assigned and not updated after (xhr)requests.
  • Some suggest the localStorage to save session ids etc. But all scripts can access it and this might be XSS security issue. Cookies work around this issue by using the httponly flag.
  • iOS: There are some modifications which will change the webView behaviour to support cookies. But they seem not to work with iOS 6 and PhoneGap 2.5: https://groups.google.com/forum/?fromgroups=#!topic/phonegap/ZJE1nxX63ow
  • Cookies seem to be enabled by default in the AppDelegate.m (v2.5).
like image 247
Bernd Avatar asked Mar 11 '13 21:03

Bernd


3 Answers

Friend, I've tried too without success to use cookies with phonegap. The solution was use localStorage.

Key Quick Example:

 var keyName = window.localStorage.key(0);

Set Item Quick Example:

 window.localStorage.setItem("key", "value");

Get Item Quick Example

 var value = window.localStorage.getItem("key");
 // value is now equal to "value"

Remove Item Quick Example:

 window.localStorage.removeItem("key");

Clear Quick Example:

 window.localStorage.clear();

If you use you javascript for both mobile and web, you can use this code to detect that enviroment:

var wl = window.location.href;
var mob = (wl.indexOf("android")>0);

References: http://docs.phonegap.com/en/1.2.0/phonegap_storage_storage.md.html#localStorage http://cordova.apache.org/docs/en/6.x/cordova/storage/storage.html#page-toc-source

Be aware: using anonymous navigation on iOS may make localstorage not work like spected. A simple test that are working fine to me:

$(document).ready(function () {
    try {
        localStorage.setItem('test', '1');
    } catch (Err) {
        if (Err.message.indexOf('QuotaExceededError') > -1) {
            // Tell the user they are in anonymous mode
            // Sugest it to go to https://support.apple.com/pt-br/HT203036 to get help to disable it
            }
        }
    }
});
like image 112
Tiago Gouvêa Avatar answered Nov 19 '22 08:11

Tiago Gouvêa


Similar to you I wanted to use cookies set by a server within my application so that my app would be consistent with the web and not require a separate device-ID or other method for authentication.

What I discovered is the following:

  • Cookies set via AJAX (e.g. jQuery $.get() or $.post()) do not persist
  • Cookies set in an 'inAppBrowser' do persist.

The way to thus get a cookie to persist is to use the inAppBrowser plugin.

First, setup a simple server that accepts as GET parameter key-value parameters you want to persist. I'm a python/tornado guy, so my server might look like:

class PersistCookieHandler(tornado.web.RequestHandler):
   @tornado.gen.coroutine
   def get(self):
      token = self.get_argument('token')
      self.set_secure_cookie('token',token)

Then, in your app:

function persistToken(token,success_cb, error_cb) {
    // replace with your URL
    url = 'SECURE_SERVER_URL_THAT_HANDLES_SET_COOKIE';  

    // _blank tells inAppBrowser to load in background (e.g., invisible)
    var ref = window.open(url, '_blank', 'location=no,toolbar=no');

    // attach a listener to the window which closes it when complete
    ref.addEventListener('loadstop', function(event) { 
        ref.close();
        success_cb();  // call our success callback
    });

    // attach a listener for server errors 
    ref.addEventListener('loaderror', function(event) { 
        // call our error callback
        error_cb(event);    
    });
}

You can then call this as follows:

persistToken(
   someToken,
   function() {
       console.log("token persisted");
   },
   function() {
       console.log("something went wrong);
   }
);
like image 6
Mike N Avatar answered Nov 19 '22 07:11

Mike N


Use the device_id to address certain records on server side. Create a database table named session on your server with device_id, cookiename, cookievalue and timestamp as columns.

When a client accesses your web server via phonegap app, get his device_id and store the cookies in your table. The device_id here acts as the access token in OAuth protocol.

Now for security reasons you need to reduce the validity period of those records, because the device_id is permenant and your client would want to sell their phones one day. Therefore, use timestamp to store the last access by the client, and delete the record if it has not been accessed for, say 10 days.

like image 4
Abdullah Al-Salloum Avatar answered Nov 19 '22 08:11

Abdullah Al-Salloum