- What is Same Origin Policyapp
Same origin policy allows only the same origins to share data to prevent Cross-site Request Forgery attacks. Same origin is depending on the protocol, port and domain name. Same origin resource sharing is open and freely accessible but different domain sharing resource is limited. Cross-domain AJAX requests are forbidden because of their ability to perform POST, PUT and DELETE requests and other types of HTTP requests which create security issues.less
- What is CORSdom
CORS (Cross Origin Resource Sharing) is a mechanism that allows different origins to share resources by setting a special header. By adding in the header a specific origin, you are allowing only this origin to load resources from this API. So you can’t use CORS unless the owner of the Server side application gives you access.ide
- An Exampleui
We are using an API implemented in Codeigniter by using REST SERVER. Our API is in a different domain than our page that uses it. One solution was to enable browser extensions on all the browsers that allows CORS resource sharing, but not all of them have an available one.this
Instead of adding the extension on each browser, we preferred to set the Access-Control-Allow-Origin header in the API responses:rest
header('Access-Control-Allow-Origin: *');
This is not recommended though because it allows any origin to access the resources API. It is suitable though for the cases that the content must be publicly available or in the object-capabitity model, where pages have unguessable URLs and are meant to be accessible to anyone who knows the secret.code
Also, we can allow only specific methods to be accessible which is safer when we don’t want to allow any origin to be able to use the POST or DELETE method for instance.orm
You can allow all of the methods by adding this:ci
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
In the case of REST SERVER we are setting the specific headers to the constructor of the REST SERVER Controller.
Rest Server constructor changes
public function __construct($config = 'rest') { header('Access-Control-Allow-Origin: *'); header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE"); parent::__construct(); }