Cross-Origin Access Settings
1. What is Cross-Origin?
Cross-origin refers to a document or script from one domain attempting to request resources from another domain. Broadly, cross-origin includes:
- Resource redirection: A links, redirects, form submissions
- Resource embedding: DOM tags such as
<link>,<script>,<img>,<video>, and external file references in stylesheets likebackground:url(),@font-face(), etc. - Script requests: Ajax requests, cross-origin operations on DOM and JavaScript objects, etc.
However, what we commonly refer to as cross-origin is a narrower concept—a type of request scenario restricted by the browser's same-origin policy. The same-origin policy is the most core and fundamental security policy of browsers. It restricts how documents or scripts loaded from one origin can interact with resources from another origin. This helps block malicious documents and reduce potential attack vectors. The same origin is defined by the protocol, domain, and port being identical. When any one of these three (protocol, domain, port) in a request URL differs from the current page URL, it is considered cross-origin. The restrictions of the same-origin policy are as follows:
- Cannot read Cookies, LocalStorage, or IndexDB from a different origin
- Cannot access the DOM or JavaScript objects from a different origin
- Cannot send Ajax requests to a different origin
2. Cross-Origin Solutions
Common cross-origin solutions include:
- Cross-origin via JSONP
- Cross-Origin Resource Sharing (CORS)
- Nginx proxy for cross-origin
- Cross-origin via postMessage
- Cross-origin via WebSocket protocol
- ...
Developers should choose the most suitable solution based on the actual situation. Below, we introduce cross-origin solutions related to the Polyv video playback service.
1. Cross-origin via JSONP
HTML tags such as <script> and <img> that fetch resources are not restricted by cross-origin policies. Based on this principle, a webpage can add a <script> to request JSON data from the server. The server, upon receiving the request, places the data in the parameter position of a callback function with a specified name and sends it back.
JSONP is a common method for cross-origin communication between servers and clients. Its biggest advantages are simplicity, applicability, and good compatibility (compatible with older versions of IE). The downside is that it only supports GET requests.
Native Implementation:
<script src="http://www.domain2.com:8080/login?user=admin&callback=handleCallback"></script>
// 向服务器test.com发出请求,该请求的查询字符串有一个callback参数,用来指定回调函数的名字
// 处理服务器返回回调函数的数据
<script type="text/javascript">
function handleCallback(res){
// 处理获得的数据
console.log(res);
}
</script>
````
**Server Response Data:**
`````javascript
handleCallback({"status":true,"user":"admin"})
````
**jQuery Ajax:**
`````javascript
$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get',
dataType: 'jsonp', // 请求方式为jsonp
jsonpCallback: "handleCallback", // 自定义回调函数名
data: {}
});
````
**Vue.js:**
`````javascript
this.$http.jsonp('http://www.domain2.com:8080/login', {
params: {},
jsonp: 'handleCallback'
}).then((res) => {
console.log(res);
})
````
### 2. Cross-Origin Resource Sharing (CORS)
Cross-Origin Resource Sharing (CORS) is a W3C standard. Currently, all browsers support this feature (IE8/9 require the XDomainRequest object to support CORS), and CORS has become the mainstream cross-origin solution. For details, see [Detailed Explanation of HTTP Access Control CORS](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS?spm=a2c4g.11186623.2.17.3a144c07qIJgKr).
- Normal cross-origin request: Only the server needs to set **Access-Control-Allow-Origin**; no frontend settings are required.
- Cross-origin request with cookies: Both frontend and backend need to be configured.
**Frontend Settings:**
**1.) Native Ajax**
`````javascript
var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容
// 前端设置是否带cookie
xhr.withCredentials = true;
xhr.open('post', 'http://www.domain2.com:8080/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('user=admin');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
````
**2.) jQuery Ajax**
`````javascript
$.ajax({
url: 'http://www.domain2.com:8080/login',
type: 'get',
data: {},
xhrFields: {
withCredentials: true // 前端设置是否带cookie
},
crossDomain: true, // 会让请求头中包含跨域的额外信息,但不会含cookie
});
````
**3.) vue-resource**
`````javascript
Vue.http.options.credentials = true
````
**4.) axios**
`````javascript
axios.defaults.withCredentials = true
````
**Server Settings:**
Server-side support for CORS is primarily achieved by setting Access-Control-Allow-Origin. If the browser detects the appropriate settings, it allows Ajax to make cross-origin requests.
**1.) Java Backend**
`````java
/*
* 导入包:import javax.servlet.http.HttpServletResponse;
* 接口参数中定义:HttpServletResponse response
*/
// 允许跨域访问的域名:若有端口需写全(协议+域名+端口),若没有端口末尾不用加'/'
response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com");
// 允许前端带认证cookie:启用此项后,上面的域名不能为'*',必须指定具体的域名,否则浏览器会提示
response.setHeader("Access-Control-Allow-Credentials", "true");
// 提示OPTIONS预检时,后端需要设置的两个常用自定义头
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");
````
**2.) PHP Backend**
`````php
<?php
header("Access-Control-Allow-Origin:*");
````
### 3. Flash Player Cross-Origin Configuration
When the Flash player requests authorization playback and marquee interfaces, it needs to be configured to allow cross-origin requests. The configuration method is: add a `crossdomain.xml` file to the root directory of the playback domain.
**Content of crossdomain.xml file:**
`````xml
<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy>
<allow-access-from domain="*"/>
<allow-http-request-headers-from domain="*" headers="*" secure="false"/>
</cross-domain-policy>
````
