What is CORS ?

As a security reasons, web browsers implement same-origin policy, which means requesting data from same domain is allowed. Data requested using different domain will throw an error.

CORS (Cross-Origin Resource Sharing) is a http-based mechanism that enables the browser to access resources outside a given domain.

When a browser makes a cross-origin request, it will add an http Origin header that states the protocol and port number. The server responds and add an "Access-Control-Allow-Origin" header in the response to browser.

If the header's origin is the same as the origin sent in the request then access to the resourse is granted. The CORS mechanism supports secure cross-origin requests and data transfers between browsers and servers.

###  What kind of requests uses CORS ?
CORS enable the cross origin requests like:
1. Access CSS resource like web-fonts , images etc. 
2. Invocations of the XMLHttpRequest or Fetch APIs (The Fetch API provides an interface for fetching resources. )

### CORS with Preflight Requests
Some HTTP methods (except GET, POST, HEAD) require a preflight request before the main request is sent to the server.
Preflight request start with the browser sending an HTTP OPTION request with the proposed request method of the main request. 


	OPTION/
    Host: www.myservice.com
	Origin: http://www.myclient.com
	Access-Control-Request-Method: POST

The server will respond with the Access-Control-Allow-Method header. If the browser requesting a method that resource holder consider invalid then request fails with error. If not, request is accepted and the main CORS request follows. If server willing to accept the request then server respond as follow:
    HTTP 200 OK
    Access-Control-Allow-Origin: http://www.myclient.com
    Access-Control-Allow-Methods: POST, GET, OPTIONS
	Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
	Access-Control-Max-Age: 86400
The response from server may also contain an Access-Control-Max-Age" header that specify the time the response must be cached within . Using this header the browser/client won't need to send a preflight reqeust everytime it want to access the CORS resource. ### How to enable CORS in Chrome browser ? You can disable the same origin security policy in chrome browser using following command. *Note : Close all the chrome instances before running below command* ``` chrome.exe --disable-site-isolation-trials --disable-web-security --user-data-dir="[some_user_directory]" ``` when you open chrome browser again you might get message prompt like: ``` You are using an unsupported command-line flag: --disable-web-security. Stability and security will suffer. ```

Comments

Popular posts from this blog

Creating simple Maven multi module project in Java

Tricky Java Questions

How to update existing CCDT file (AMQCLCHL.TAB) for successful MQueue connection