2015年4月9日 星期四

Same Origin Policy /Cross Domain Issue

Ref: http://www.restapitutorial.com/resources.html

Handling Cross-Domain Issues 

We've all heard about working around the browser's same origin policy or common-source requirement. In other words, the browser can only make requests to the site it's currently displaying. For example, if the site currently being displayed is www.Example1.com, then that site cannot perform a request against www.Example2.com. Obviously, this impacts how sites access services.

Presently, there are two widely-accepted methods to support cross-domain requests: JSONP and CrossOrigin Resource Sharing (CORS). JSONP or "JSON with padding" is a usage pattern that provides a method to request data from a server in a different domain. It works by the service returning arbitrary JavaScript code instead of JSON. These responses are evaluated by the JavaScript interpreter, not parsed by a JSON parser. CORS, on the other hand, is a web browser technology specification, which defines ways for a web server to allow its resources to be accessed by a web page from a different domain. It is seen as a modern alternative to JSONP and is supported by all modern browsers. Therefore, JSONP is not recommended. Choose CORS whenever and wherever possible.

Supporting CORS 

Implementing CORS on a server is as simple as sending an additional HTTP header in the response, for example:

Access-Control-Allow-Origin: *

An access origin of '*' should only be set if the data is meant for public consumption. In most cases the Access-Control-Allow-Origin header should specify which domains should be able to initiate a CORS request. Only URLs that need to be accessed cross-domain should have the CORS header set.

Access-Control-Allow-Origin: http://example.com:8080 http://foo.example.com

Allow only trusted domains in Access-Control-Allow-Origin header.

Access-Control-Allow-Credentials: true

Use this header only when necessary as it will send the cookies/sessions if the user is logged into the application.

These headers can be configured via the Web server, proxy or sent from the service itself. Implementing it within the services is not recommended as it's not flexible. Instead, use the second form, a space delimited list of appropriate domains configured on your Web server. More about CORS can be found at: http://enable-cors.org

沒有留言:

張貼留言