CORS – Cross Origin Resource Sharing – A Simple Example

Local setup (I did it on Windows 7 and IIS): 1. Created two websites made to run on two different ports. In IIS a new website can be created using the option shown the screen shot below: clip_image001 A note about Same Origin: Note that most of the modern browsers define the following combination as “same origin” – Scheme (protocol), domain and Port number. As far as I know Internet Explorer tends to behave differently as it did not consider the port number but my memory may need a refresh with the latest releases, other browsers are quire consistent. The two sites I created were accessible using the following URLs:

i. http://localhost:8098/ – I called it Site 1 ii. http://localhost:8099/ – I called it Site 2

So for the sake of SoP these two are different origin sites even though they are on the same web server sitting in two adjacent folders 🙂 I created three landing pages:

i. cors.php on Site 1 ii. site1processor.php on site 1 iii. site2processor.php on site 2

The code for each is as below: cors.php – Site 1 on port 8098 accessible via url: http://localhost:8098/cors.php image site2processor.php – Site 2 on port 8099 accessible via URL: http://localhost:8098/ site1processor.php  image site2processor.php – Site 2 on port 8099 accessible via URL: http://localhost:8099/ site2processor.php image I un-commented the following snippet in the cors.php file: image This request submits a request to the Site1 which is “same origin” as the cors.php. The request executes just fine and the “Success” alert pops up. No I comment the above code and un-comment the following snippet: image This request submits a request to Site 2 which is a different domain from the one where the cors.php file is hosted. Looking at the console windows of the developer tools (Chrome-F12) I see the following message: clip_image003 That is Site 2 does not permit access to its pages from any other domain. In case Site 2 wants to allow access to some content from other domains, there is an option to enable that: Access-Control-Allow-Origin header I tried the Access-Control-Allow-Origin header option by adding this header to the response from the site2processor.php file. The code for site2processor.php now looks like below: image What the above code change effectively does is allow access to the page site2processor.php hosted on Site 2 from Site 1. Now the following line of code is executed from the http://localhost:8098/cors.php the success pop up is displayed implying that the request was successful image


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s