Secure communication in a web-service using PhoneGap - ajax

I am going to develop a PhoneGap application which is pretty simple.
I need to implement an authentication and some simple data transfer from the phone to the server and vice versa.
I prefer to use ASP.NET as a webservice and our database is MS SQL, but I am not sure what approach I should take to create a secure communication between PhoneGap App and the webservice.
The problem with a simple AJAX request is limitation in cross-domain and I’m not sure if JSONP is a good option.
I was wondering if someone can tell me what technology I should use in order to make a semi secure connection which works with PhoneGap (HTML5, JavaScript) and .NET webservice.
I understand that it’s a general question but I need to know what technology is the best in such a case.
Thanks.

For starters you may use rest interfaces and http authentication, it will be simple and it will help you get going.

JSONP is a good option as long as you sanitize(validate) the input you receive from your request. Furthermore its supported from jquery so you could use something like:
function retrieve(parameter1,parameter2, server)
{
var url1 = 'http://' + server + '/endpoint.php?jsoncallback=?';
$.getJSON(url1,
{
param1: parameter1,
param2: parameter2,
},
function(data)
{
console.log('Data connection OK');
retData = data;
});
}
Regarding security, you could do this request over HTTPS.
At server side, the json reply should be wrapped in a function with the name taken from jsoncallback so you could achieve JSONP.

Related

How to call ajax from Excel JS API

I am new to Office.js API. I am trying to develop Web Add-In for Excel and I need to get data from WebAPI for this I am trying to use ajax but its not working
Here is very simple Ajax code
$.ajax({
url: "http://localhost:61721/api/values",
type: "GET",
dataType:"JSONP",
success: function (data) {
$("#div1").html(JSON.stringify(data));
},
error:function(error){}
});
Update
Is there any alternative way other than Ajax in Office.js through which we can get data from Web API?
From the client, AJAX requests must be send to SSL URIs and those URIs must be declared in AppDomain list of the app manifest. Please refer to: Send POST AJAX request from Office Add-In.
In the same time, if your app has server side portion of code, you may send direct request to any Web API from there. Nobody limit you in technology (REST, microservices, etc.) and nobody check your connection is secure, when using 3rd party resources from your server.

Does the server need to know the client is using jsonp?

We have a existing server which receives POST data and respond with json. The server is using Django. I am developing an webpage game using the json data. However I figured out I may need to use jsonp because the game is hosted on another domain. I want to know if the server need to know I am using jsonp (i.e. does the server need to change the code) or it is completely transparent to the server side? I cannot reach the server developer so I hope I can get advise here. Thank you very much!
Yes, server must respond differently - JSNOP requires that JSON response is wrapped in some sort of function call.
wrapperFunc({"Name": "Foo", "Id": 1234, "Rank": 7});
Note that securing JSONP against Cross-site request forgery is harder than using proper CORS which you may be able to use if you don't need to target old versions of IE.

How to perform cross-site ajax request?

Browsers don't allow cross-site AJAX calls (it's a security restriction).
Is there any possible solution ?
EDIT
I control only the caller website
If you control both parties then there a lot of options. Such as JSONP, or modifying header responses of the remote website. Unfortunately, JSONP only works if the remote website supports it. You can't force a JSONP call to a website that doesn't already support it.
However, as you have said, you only control the source website. You cannot hack the browser around this restriction for obvious reasons. You do have a third option which is creating a back-end proxy. You can use Apache and mod_rewrite to create a proxy. Here is on how to do this or this link which is more detailed.
For example
ProxyPass /api/gtalkbots http://gtalkbots.com/reverse-proxy-data.php
ProxyPassReverse /api/gtalkbots http://gtalkbots.com/reverse-proxy-data.php
Creates a proxy at /api/gtalkbots which will returns the repose from gtalkbots.com
Your best solution is to use JSONP calls.
function jsonp(url, params, callback){
var script = document.createElement("script");
script.setAttribute("src", url+'?'+params+'&callback='+callback);
script.setAttribute("type","text/javascript");
document.body.appendChild(script);
}
function doit(data){
alert(data);
}
jsonp('http://domain.com', 'foo=bar', 'doit');
In the opposite side, the website you're contacting must be able to return a JSONP formatted response in order for this to work.
There are 2 ways to do this, depending on whether the callee will ship out JSONP or not:
1. If you can, use JSONP
JSONP is a way to bypass the cross domain policy by returning a function call, rather than a naked JSON object. The P stands for padding, essentially just the part that calls the function.
For this to work, the callee needs to return JSONP.
Regular JSON looks like this:
{a: 12, b: 15}
JSONP looks like this:
callback({a: 12, b: 15});
When the AJAX request completes, the callback function (which you define in your own code) will be executed and the JSON data passed to it as an object, thus bypassing the cross domain policy.
2. If JSONP is not supported, mirror the request through your own server
The second option is to pipe data through your own server. Your JavaScript makes a request from your server, and the server then mirrors that request to the remote server and pings back the result.
Since the AJAX request is now made to your own server you won't run afoul of the cross domain policy.
There are two downsides to this approach:
Two requests are now required which will slow the response time a little, though probably not much as server to server communication will probably be via a fat pipe.
Since all requests now originate from your server you may have problems with IP based rate limits. This is the case with Twitter API calls. You may be able to mitigate against this by caching results.

Best Practice for Handling AJAX requests from website to API provider

So, I implemented an API provider to be accessed by both web application and mobile applications.
Most likely this will not be a large scale project, but I want to maximize my learning experience and geek out where I can.
Anyway, from what I understand, it seems like it's better to put the API provider service and the actual website on separate domains to make scaling easier.
For example, twitter has the website twitter.com and api.twitter.com.
One immediate issue would be dealing with the cross-domain issue with AJAX.
From what I gather, there are 2 ways to implement cross-domain AJAX
JSONP: I heard about it, but don't know much beyond the name
Proxy Server: so, my website is build on top of ASP.NET MVC and I was thinking about creating a APIProxy controller to handle all cross-domain API requests.
That way, I would make an AJAX call via $.ajax(settings) and then pass in the website URL that corresponds to the APIProxy controller. The APIProxy controller would then make the appropriate POST server calls and process the JSON responses and return the response back to AJAX callback functions.
I heard about flXHR about I don't want to use Flash because devices like the iPad or any a lot of mobile browsers don't support Flash.
Anyway, I just wanted to ask what are some of the best practices in managing a website with the API provider on a separate domain or subdomain.
When you request some JSON, it returns an object or array. Script tags are not subject to the same-domain rule. So instead making an AJAX call, you would essentially do this:
<script src="Http://api.example.com?param1=something&etc"></script>
That would load the JSON, and it would execute as JavaScript.
...But a simple object or array "executing" by itself isn't very useful. So when you request the JSON, you also include the name of a callback function. If the provider sees that a callback was provided, instead of just returning JSON, it actually returns JavaScript: the JSON is passed to your function as an argument.
Then, when the script loads, your function (which you already defined) is called, and given the JSON to work with.
That's JSONP.
Bibliography
Newton, Aaron. "Request.JSONP." Clientcide. 7 Dec. 2009. Web. 28 Jan. 2011.

Ajax And REST: Can I send an ajax request to a REST service to recieve response?

I want to use mootools and SqueezBox class to handle a request to a RESTful service. I don't want to use any server-side script. I am using AJAX. I send a request to the following url using GET method.
http://www.idevcenter.com/api/v1/links/links-upcoming.json
but I receive a 404 error. Is it because cross-site scripting? here is my code:
SqueezeBox.initialize({handler:'url',ajaxOptions:{method:'GET'}});
$('a.modal').addEvent('click',function(e){
new Event(e).stop();
SqueezeBox.fromElement($('a.modal'));
});
In Firebug console, sometimes 'aborted' is shown and sometimes '404'.what is wrong with that?
XMLHttpRequest is subject to the Same Origin Policy; if the document your JavaScript is running within is not from the same origin as the service you're trying to call, the call will be disallowed for security reasons.
There is now a proposed standard for cross-origin resource sharing to address this. It may be that the service you're trying to use supports it; if so, using a browser that implements CORS (recent versions of Firefox and Chrome do, as do some others) may work. IE8 supports it but requires that you do extra work.
You cannot use XMLHttpRequest (that is, ordinary "ajax") to call a service on a server that is not in your domain.
You can, however, use the JSONP trick, which takes advantage of the fact that the browser will load Javascript from other domains. However, the service has to know that you're going to do that, and it has to understand the protocol. That particular service seems perfectly willing to give me a JSON response, but it doesn't pay attention when I give it a "callback" parameter. (I've tried both "callback" and "jsonp" and the JSON blob that comes back is the same, without a function call wrapper.)

Resources