Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Phonegap file transfer and Access-Control-Allow-Origin

Just curious tried using phonegap with ajax to query from server notice my ip gets blocked after some time due to Access-Control-Allow-Origin not being allowed. The app still functions until you get blocked though.

Found a way around this is either jsonp or allow access control on server. But jsonp cannot transfer files so the 2nd is the option to take for file upload.

Code for allowing access control on server:

<?php header('Access-Control-Allow-Origin: *'); ?>

Does ft.upload of phonegap also need this?

Another question is there a way to only allow only a specific phonegap app for this?

Since you can change the * to specific url but not sure how to do this for phonegap.

Thanks

like image 759
jhdj Avatar asked Oct 22 '22 06:10

jhdj


2 Answers

PhoneGap has the options to define this in the config.xml file.

http://docs.phonegap.com/en/3.2.0/guide_appdev_whitelist_index.md.html#Whitelist%20Guide

<access origin="http://google.com" />

<access origin="https://google.com" />

<access origin="http://*.google.com" />

<access origin="*" />
like image 181
Purus Avatar answered Nov 03 '22 04:11

Purus


To only allow a specific app to work with your server, what you can do is to send through headers with your AJAX request a private key, like "X-ACCESS-TOKEN".

$.ajax({
   type: 'POST',
   url: url,
   headers: {
      "X-ACCESS-TOKEN":"CLIENT_SECRET_KEY",
   }

Then on your server you can check if the headers has been sent and if it's equal to the expected value.

Also I would advise to handle the header using your .htaccess instead of doing it directly in the code of your backend.

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, accept, X-ACCESS-TOKEN"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Note that if you follow my suggestion, you will have to add the X-ACCESS-TOKEN to the allowed headers list.

like image 40
beNjiox Avatar answered Nov 03 '22 04:11

beNjiox