Handling cookies in PhoneGap / Cordova

I am working on a PhoneGap application using a server session. Cookies are required to process the session. In addition, you must process the cookie from the load balancer. So there is no way around. How do you handle cookies in PhoneGap?

I have already done some research:

  • Some say cookie processing may depend on the server not setting cookies for unknown user agents (IIS): PhoneGap session (cookies) on iOS
  • Javascript cookies can set document.cookie = ... files, but they are not stored in PhoneGap and are not lost. Before running xhr requests, it works.
  • Cookies can be restored after an xhr request using xhr.getResponseHeader ('Set-Cookie'). But only when it is really installed on the server. Unfortunately, jQuery breaks the cookie header.
  • The JavaScript document.cookie property is not assigned or updated after (xhr) requests.
  • Some suggest localStorage to save session identifiers, etc. But all scripts can access it, and this could be an XSS security issue. Cookies work around this issue using the httponly flag.
  • iOS: There are some changes that will change the behavior of webView to support cookies. But they don't seem to work with iOS 6 and PhoneGap 2.5: https://groups.google.com/forum/?fromgroups=#!topic/phonegap/ZJE1nxX63ow
  • Cookies appear to be enabled by default in AppDelegate.m (v2.5).
+83
cookies cordova
Mar 11 '13 at 21:41
source share
9 answers

Friend, I also tried unsuccessfully with cookies with a telephone connection. The solution was to use localStorage.

Key Quick Example:

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

Quick set of elements:

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

Get quick example item

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

Delete item Quick example:

  window.localStorage.removeItem("key"); 

Clear Quick example:

  window.localStorage.clear(); 

If you use javascript for mobile and web sites, you can use this code to detect this environment:

 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 in iOS may result in localstorage not working as shown. A simple test that works great for 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 } } } }); 
+64
May 15 '13 at 12:23
source share

Like you, I wanted to use the cookies set by the server in my application so that my application was web-based and did not require a separate device identifier or other authentication method.

I found the following:

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

Thus, to save the cookie, you must use the inAppBrowser plugin.

First, set up a simple server that accepts the GET key parameter settings that you want to save. I am a python / tornado guy, so my server might look like this:

 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 application:

 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 (eg, 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); }); } 

Then you can call it like this:

 persistToken( someToken, function() { console.log("token persisted"); }, function() { console.log("something went wrong); } ); 
+4
Dec 07 '15 at 10:53
source share

You can also add a session identifier to the requesting URL and, depending on the language of the application server, retrieve the session data using the session identifier value of the query string that you passed - for example, in PHP you can open an existing session by passing the session identifier, Although this is not recommended because of the risks of session hijacking, you can easily check the IP and browser to make sure that the session is coming from the same client. Of course, this will require the expiration of your session as soon as the client closes the session browser and limits you to caching views, since the session will be included in the actual html. Storing data on a local device for me, at least, is not really an option, because it exposes the client too much, which, in my opinion, is much more important for security.

+3
Jun 06 '13 at 11:28
source share

Use device_id to address specific server-side entries. 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 through the phonegap application, get its device_id and save the cookies in its table. device_id here acts as an access token in the OAuth protocol.

Now, for security reasons, you need to reduce the validity period of these entries, because device_id permenant and your client will want to sell their phones one day. Therefore, use timestamp to store the last access by the client and delete the entry if there was no access to it, for example 10 days.

+2
Aug 24 '14 at 4:55
source share

I am using Cordova 6.1 (the latest version at the moment), and actually I found the following:

If I set the cookie via Javascript using document.cookie = ... then this will not work. However, if I send the setCookie function via Ajax to the server using a function like

 function setCookie(name, value, exdays) { if(isPhonegap() === true){ var data = "typ=function&functionType=setCookie&name="+name+"&value="+value+"&exdays="+exdays; loadAjax(data, false); } else if (!(document.cookie.indexOf("name") >= 0)){ var expires; if (exdays) { var date = new Date(); date.setTime(date.getTime()+(exdays*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } else{ expires = ""; } document.cookie = name+"="+value+expires+"; path=/"; } } 

and set the server side cookie using

 setcookie($cookie, $value, $expires , "/" ); 

then it really works!

Hope this helps. Greetings

+2
Mar 31 '16 at 13:26
source share

Had the same problem and decided to move evrth to localStorage I wrote a plugin so you can use it as well: angular-cookies-mirror

0
Jan 08 '17 at 2:05 on
source share

Of course you can.

the ionic application just sends ajax requset, the cookie works well or is server independent.

I have work with Django python server and node server, both cookies work very well

node code below

 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", '*'); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("Access-Control-Allow-Credentials",true); next(); }); 

rest api

 router.get('/setCookies', function(req, res, next) { var now = new Date(); var nextYear=new Date(now.setFullYear(now.getFullYear()+1)); //you can change the cookie key and value by your self here res.cookie('cookiesTest', 'set cookies success,your cookies can be set by server', { expires: nextYear, httpOnly: true }); res.status(200) res.end('SET COOKIES SUCCESS') }); router.get('/getCookies', function(req, res, next) { res.status(200) res.end(JSON.stringify(req.cookies)) }); 

ion application code

 var server='http://[YOUR IP HERE]:3000' $scope.setCookies=function() { $http({ url: server + '/setCookies', method: 'GET' }).success(function (data, header, config, status) { alert('set cookies success,look console') $scope.setCookiesStatu=false console.log(data) $scope.cookiesValue=data }).error(function (data, header, config, status) { alert('set cookies error,check console or your server address is wrong') console.log(data) }); } $scope.getCookies=function() { $http({ url: server + '/getCookies', method: 'GET' }).success(function (data, header, config, status) { alert('get cookies success,look console') console.log(data) $scope.cookiesValue=data }).error(function (data, header, config, status) { alert('get cookies error,check console or your server address is wrong') console.log(data) }); } 

you can check my source code here

0
Aug 24 '17 at 7:52
source share

I think the question is how to configure client-side cookies for the Cordova app. Most of the information on this topic implies that setting client-side cookies does not work for cordova.

But I found a plugin that allows me to set client cookies for my Cordova application.

Check out https://www.npmjs.com/package/cordova-plugin-cartegraph-cookie-master .

It just works!

0
Apr 14 '19 at 18:38
source share

I also had problems with a session cookie with Cordova + XHR requests. Cookies are lost every time you restart the application. Two things solved my problems:

  1. Cookies must have an expiration date.

  2. All XHR requests must have the withCredentials flag set to true.

0
Jul 15 '19 at 14:45
source share



All Articles