JSONP in non jsonp supported site - json

I have a requirement where I have to get data from another server .. The server supports only JSON and not JSONP. How can I get the data from the server using JSONP?
I am doing it in jquery..
Is there any other solution to it?
Kindly help me..

The reason why JSONP exists is to get around the cross-domain issue with Javascript. This basically means that javascript in your browser shouldn't be allowed to talk to webservices that's not on the same domain as your web application.
JSONP makes this cross-domain integration possible because your browser and the server have an "agreement". You give it a callback, and it gives you the result, wrapped in that callback. It expects to be called via javascript so there's less of a security risk involved.
Example:
You call http://www.abccorp.com/index.php?callback=somevalue
Without JSONP, you'd get back:
{ some: 'value' }
With JSONP:
somevalue({ some: 'value' });
If a server does not support this callback, it's just not possible (by only using javascript).
I recommend using a server-side programming language that can facilitate this call for you.
For example, you have a PHP file called index.php. Your javascript would call this file using an AJAX JSON request. In turn, it would call the server you need, get the results, and forward them to the javascript. Since you're not using javascript, this server-side programming does not need a callback (or agreement) like javascript does.

Related

Is it necessary to pass request data as JSON string to server

When making an AJAX request to a server (may be Java, PHP, etc), is it necessary to pass data as JSON string ?
Can we not pass the object directly ? Are there issues de-serializing OR can that be handled at the backend ? Any examples of handling JS object (if it is possible to send an obj directly) at the backend would be great ?
Object literal makes sense only in the JavaScript runtime environment. Since AJAX body is simply a string, you can pass {a:3} to a server. But what should server side do with it? It ertainly can store it in a database and return to you back when requested. But what if it wanted to extract some data from it? You' have to have JS runtime and evaluate the object using eval. Which would be awkward, but possible. However, not all servers have JS runtime environment. Whereas there are libraries for many languages that support parsing JSON into the representation specific to the language on the server.
An AJAX request passes data to the server in the same way any other HTTP request does. Most commonly, AJAX requests use POST and pass data to the server as POST data, but query strings are often used, and there are other ways to pass data to a server using HTTP and AJAX.
In essence all HTTP data is octets (bytes), and HTTP has no special support for serialization of JavaScript objects, so you or the libraries and/or frameworks you use must handle the serialization.

Preventing access to JSON data in an Angular app

I got a (Flask) backend powering an API that serves JSON to an Angular app.
I love the fact that my backend (algorithms, database) is totally disconnected from my frontend (design, UI) as it could literally run from two distinct servers. However since the view is entirely generated client side everyone can access the JSON data obviously. Say the application is a simple list of things (the things are stored in a JSON file).
In order to prevent direct access to my database through JSON in the browser console I found these options :
Encrypting the data (weak since the decrypting function will be freely visible in the javascript, but not so easy when dealing with minified files)
Instead of $http.get the whole database then filtering with angular, $http.get many times (as the user is scrolling a list for example) so that it is programmatically harder to crawl
I believe my options are still weak. How could I make it harder for a hacker to crawl the whole database ? Any ideas ?
As I understand this question - the user should be permitted to access all of the data via your UI, but you do not want them to access the API directly. As you have figured out, any data accessed by the client cannot be secured but we can make accessing it a little more of PITA.
One common way of doing this is to check the HTTP referer. When you make a call from the UI the server will be given the page the request is coming from. This is typically used to prevent people creating mashups that use your data without permission. As with all the HTTP request headers, you are relying on the caller to be truthful. This will not protect you from console hacking or someone writing a scraper in some other language. #see CSRF
Another idea is to embed a variable token in the html source that bootstraps your app. You can specify this as an angular constant or a global variable and include it in all of your $http requests. The token itself could be unique for each session or be a encrypted expiration date that only the server can process. However, this method is flawed as well as someone could parse the html source, get the code, and then make a request.
So really, you can make it harder for someone, but it is hardly foolproof.
If users should only be able to access some of the data, you can try something like firebase. It allows you to define rules for who can access what.
Security Considerations When designing web applications, consider
security threats from:
JSON vulnerability XSRF Both server and the client must cooperate in
order to eliminate these threats. Angular comes pre-configured with
strategies that address these issues, but for this to work backend
server cooperation is required.
JSON Vulnerability Protection A JSON vulnerability allows third party
website to turn your JSON resource URL into JSONP request under some
conditions. To counter this your server can prefix all JSON requests
with following string ")]}',\n". Angular will automatically strip the
prefix before processing it as JSON.
For example if your server needs to return:
['one','two'] which is vulnerable to attack, your server can return:
)]}', ['one','two'] Angular will strip the prefix, before processing
the JSON.
Cross Site Request Forgery (XSRF) Protection XSRF is a technique by
which an unauthorized site can gain your user's private data. Angular
provides a mechanism to counter XSRF. When performing XHR requests,
the $http service reads a token from a cookie (by default, XSRF-TOKEN)
and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript
that runs on your domain could read the cookie, your server can be
assured that the XHR came from JavaScript running on your domain. The
header will not be set for cross-domain requests.
To take advantage of this, your server needs to set a token in a
JavaScript readable session cookie called XSRF-TOKEN on the first HTTP
GET request. On subsequent XHR requests the server can verify that the
cookie matches X-XSRF-TOKEN HTTP header, and therefore be sure that
only JavaScript running on your domain could have sent the request.
The token must be unique for each user and must be verifiable by the
server (to prevent the JavaScript from making up its own tokens). We
recommend that the token is a digest of your site's authentication
cookie with a salt for added security.
The name of the headers can be specified using the xsrfHeaderName and
xsrfCookieName properties of either $httpProvider.defaults at
config-time, $http.defaults at run-time, or the per-request config
object.
Please Kindly refer the below link,
https://docs.angularjs.org/api/ng/service/$http
From AngularJS DOCs
JSON Vulnerability Protection
A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string ")]}',\n". Angular will automatically strip the prefix before processing it as JSON.
There are other techniques like XSRF protection and Transformations which will further add security to your JSON communications. more on this can be found in AngularJS Docs https://docs.angularjs.org/api/ng/service/$http
You might want to consider using JSON Web Tokens for this. I'm not sure how to implement this in Flask but here is a decent example of how it can be done with a Nodejs backend. This example at least shows how you can implement it in Angularjs.
http://www.kdelemme.com/2014/03/09/authentication-with-angularjs-and-a-node-js-rest-api/
Update: JWT for Flask:
https://github.com/mattupstate/flask-jwt

Angular.js : CORS HttpInterceptor that transforms $http.get into $http.jsonp request transparently

I've been looking into if it's possible to create a web based version of my Chrome Plugin
now that it's relying completely on Trakt.TV's JSON API.
According to angular's documentation, it's possible to intercept HTTP requests at several levels, one is the HTTP Backend itself (mainly used for testing though) and the other is HTTPInterceptor.get
The basic idea is to wrap calls to Trakt.TV's JSONP api through http://json2jsonp.com/ and have them returned transparently to get around cross site scripting restrictions. This would not only be very useful for my own project, but for a lot of other people daeling with the same issues too (therefore i'll release the module after it's done, but I want to do it properly)
The basics should be simple:
Hook the $http.get request at the right level
Overwrite the original request made
Cancel an optional other request already set up
Hook it through $http.jsonp(http://json2jsonp.com/)
Return the original promise's success/fail when done
Questions:
Has anyone built anything like this yet? (Github searches revealed nothing)
Would you suggest using the HTTPBackend or the HTTPInterceptor?
why can't you just use the jsonp helper function?
httpBakend is a mockup service to fake a backend server is not used on live code. http interceptors would do what you want you just need to attach the callback function name to your request if the url contains what ever name you want to filter and then in the response interceptor you have to pass response to the callback function so the json to be evaluated. be aware that interceptors will inspect every request makde by angular which is not very eficien, unless you are only doing calls to the tv service.
like i said before a better approach is to use $http.jsonp function
https://docs.angularjs.org/api/ng/service/$http#jsonp
a word about interceptors they need to be defined as services and then be passed to HttpProvider during your apps configuration.

What does the 'P' in JSONP stand for?

I can't seem to find a definitive answer on this -- what does the p in JSONP stand for?. The candidates I've found so far are padding and prints. Anyone know where the JSONP name came from?
Padding.
from http://en.wikipedia.org/wiki/JSONP
JSONP or "JSON with padding" is a complement to the base JSON data
format, a pattern of usage allowing a page to request data from a
server in a different domain. JSONP is a solution to this problem,
forming an alternative to a more recent method called Cross-Origin
Resource Sharing.
Padding
While the padding (prefix) is typically the name of a callback
function that is defined within the execution context of the browser,
it may also be a variable assignment, an if statement, or any other
Javascript statement. The response to a JSONP request (namely, a
request following the JSONP usage pattern) is not JSON and is not
parsed as JSON; the returned payload can be any arbitrary JavaScript
expression, and it does not need to include any JSON at all. But
conventionally, it is a Javascript fragment that invokes a function
call on some JSON-formatted data.
Said differently, the typical use of JSONP provides cross-domain
access to an existing JSON API, by wrapping a JSON payload in a
function call.
Hope that helped. Google wins!
Stone,
What I know, it stands for 'Padding'. There is a explaination about it on Wikipedia: JsonP
What it does?
It gives you the possibility to make a CROSS-DOMAIN request and get JSON data returned.
Normally via the HTML script tag you call for another JavaScript.
But JsonP provide you a callback function and you can return noraml Json response.
Example:
You create a script tag:
<script type="text/javascript" scr="http://anotherDomain/Car?CarId=5&jsonp=GiveCarResponse"></script>
In this script the GiveCarResponse is the callback function on the other Domain. Invoking this function will result in a Json response. In example:
{"CarId":5, "Brand":"BMVV", "GAS": false}
Does this make sense?
From wikipedia, it stands for "padding" (or with padding).
http://en.wikipedia.org/wiki/JSONP
Umm ... you've seen the wikipedia page, and you mistrust its accuracy?
This standards site seems to confirm the "with padding".
It basically means to add a calling function around JSON.
AJAX can be called from your own server only and is not a cross domain. So to load data from different servers at client side, you make a JSONP request, basically you load a normal javascript file from other server just like you include a normal javascript file. Bust as JSON is not a valid javascript file, JSON is wrapped up in a function call to make it valid js file. the wrapped up function (already in your code) then extracts that data and show it on your page.

Using MVC3's AntiForgeryToken in HTTP GET to avoid Javascript CSRF vulnerability

In regards to this Haacked blog, I'm hesitant to implement the proposed anti-JSON GET hijacking solutions since
The recommended solutions to mitigating JSON hijacking involve non-REST-full JSON POSTs to GET data
The alternate solution (object wrapping) causes problems with 3rd party controls I don't have source-code access to.
I can't find a community-vetted implementation that implements the Alternative Solution (listed below) on how to compose the security token, or securely deliver it within the webpage. I also won't claim to be enough of an expert to roll my own implementation.
Referrer headers can't be relied upon
Background
This blog describes a CSRF issue regarding JSON Hijacking and recommends using JSON POSTs to GET data. Since using a HTTP POST to GET data isn't very REST-full, I'd looking for a more RESTfull solution that enables REST actions per session, or per page.
Another mitigation technique is to wrap JSON data in an object as described here. I'm afraid this may just delay the issue, until another technique is found.
Alternative Implementation
To me, it seems natural to extend the use ASP.NET MVC's AntiForgeryToken with jQuery HTTP GETs for my JSON.
For example if I GET some sensitive data, according to the Haacked link above, the following code is vulnerable:
$.getJSON('[url]', { [parameters] }, function(json) {
// callback function code
});
I agree that it isn't RESTfull to GET data using the recommended POST workaround. My thought is to send a validation token in the URL. That way the CSRF-style attacker won't know the complete URL. Cached, or not cached, they won't be able to get the data.
Below are two examples of how a JSON GET query could be done. I'm not sure what implementation is most effective, but may guess that the first one is safer from errant proxies caching this data, thus making it vulnerable to an attacker.
http://localhost:54607/Home/AdminBalances/ENCODEDTOKEN-TOKEN-HERE
or
http://localhost:54607/Home/AdminBalances?ENCODEDTOKEN-TOKEN-HERE
... which might as well be MVC3's AntiForgeryToken, or a variant (see swt) thereof. This token would be set as an inline value on whatever URL format is chosen above.
Sample questions that prevent me from rolling my own solution
What URL format (above) would you use to validate the JSON GET (slash, questionmark, etc) Will a proxy respond to http://localhost:54607/Home/AdminBalances with http://localhost:54607/Home/AdminBalances?ENCODEDTOKEN-TOKEN-HERE data?
How would you deliver that encoded token to the webpage? Inline, or as a page variable?
How would you compose the token? Built in AntiforgeryToken, or by some other means?
The AntiForgeryToken uses a cookie. Would a backing cookie be used/needed in this case? HTTP Only? What about SSL in conjunction with HTTP Only?
How would you set your cache headers? Anything special for the Google Web Accelerator (for example)
What are the implications of just making the JSON request SSL?
Should the returned JSON array still be wrapped in an object just for safety's sake?
How will this solution interop with Microsoft's proposed templating and databinding features
The questions above are the reasons I'm not forging ahead and doing this myself. Not to mention there likely more questions I haven't thought of, and yet are a risk.
The Asp.net MVC AntiForgeryToken won't work through HTTP GET, because it relies on cookies which rely on HTTP POST (it uses the "Double Submit Cookies" technique described in the OWASP XSRF Prevention Cheat Sheet). You can also additionally protect the cookies sent to the client by setting the as httponly, so they cannot be spoofed via a script.
In this document you can find various techniques that can be used to prevent XSRF. It seems the you described would fall into the Approach 1. But we have a problem on how to retrieve the session on the server when using Ajax HTTP GET request since the cookies are not sent with the request. So you would also have to add a session identifier to you action's URL (aka. cookieless sessions, which are easier to hijack). So in order to perform an attack the attacker would only need to know the correct URL to perform the GET request.
Perhaps a good solution would be to store the session data using some key from the users SSL certificate (for example the certs thumb-print). This way only the owner of the SSL certificate could access his session. This way you don't need to use cookies and you don't need to send session identifiers via query string parameters.
Anyway, you will need to roll out your own XSRF protection if you don't want to use HTTP POST in Asp.net MVC.
I came to this problem and the solution was not so trivial however there is a fantastic blog to get you started this can be used with get and post ajax.
http://johan.driessen.se/posts/Updated-Anti-XSRF-Validation-for-ASP.NET-MVC-4-RC
If you place the following in the global name space all your post/gets can take advantage having an anti forgery token and you don't have to modify your ajax calls. Create an input element in a common page.
<form id="__AjaxAntiForgeryForm" action="#" method="post">#Html.AntiForgeryToken()</form>
The following javascript will read the anti forgery tokken and add it to the request header.
// Wire up the global jQuery ajaxSend event handler.
$(document).ajaxSend(namespace.ajax.globalSendHandler);
// <summary>
// Global handler for all ajax send events.
// </summary>
namespace.ajax.globalSendHandler = function (event, xhr, ajaxOptions) {
// Add the anti forgery token
xhr.setRequestHeader('__RequestVerificationToken', $("#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]").val());
};
I think it is legitimate to use AntiforgeryToken (AFT) within an ajax http GET request provided that it is embedded in a form that already provides the AFT and associated cookie. The ajax handler can then do the validate on the server just how it would in a normal form post.