Securing API calls from cross domain using RESTful service Securing API calls from cross domain using RESTful service codeigniter codeigniter

Securing API calls from cross domain using RESTful service


Ajax requests can be emulated by creating the proper headers. If you want to have a basic check to see if the request is an Ajax request you can use:

if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') { //Request identified as ajax request }, However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

But this is not enough, you have to secure your Ajax call using server side scripting(e.g. PHP). For example, if your AJAX passes the key to the PHP file, write code in the PHP file to make sure that is the correct key.


Facebook, Google and other large companies uses iframe for these kind of services.
Take example of facebook it gives you on script to put in code which when runs will create an iframe for particular view.

Also you can not make cross-site ajax calls. Only iframe which is loaded from your site can securely load the page.

Now with the keys, you can always provide public key in script. The iframe href will point to you website with $_SERVER['http_referer'] where you can make sure the api key is authorized. Don't use private key unless you are not going to post any private confidential data.


I wrote an article awhile back on securing REST APIs, specifically those consumed by a browser. I recommend taking a look https://www.moesif.com/blog/technical/restful-apis/Authorization-on-RESTful-APIs/

Auth0, an authentication provider has quite a few resources also, I have no affiliation other than used them before and like their product.

Many APIs are secured through JWTs which are nice since they allow you to authenticate an API call without centralized auth servers. They are based on public/private crypto algorithms where the two keys are mathematically related. The keys are generated in a trusted environment such as your server, but anyone can verify that they come from who they say they did. You can design other authentication token schemes.

Depending on what you need, the keys will be accessible by any client, so you can design a specific permissions model to ensure the key has the rights of least privilege (i.e. they shouldn't have admin rights, etc)