search
HomeWeb Front-endJS TutorialDetailed explanation of JS origin policy + cross-domain access usage

This time I will bring you a detailed explanation of the use of the JS same-origin policy for cross-domain access. What are the precautions for the use of the JS same-origin policy for cross-domain access? The following is a practical case, let’s take a look.

1. What is the same-origin policy

To understand cross-domain, you must first understand the same-origin policy. The Same Origin Policy is a very important security policy implemented on browsers for security reasons.

What is the same origin:

URL consists of protocol, domain name, port and path. If the protocol, domain name and port of two URLs are the same, it means that they have the same origin. .

Same origin policy:

The browser's same origin policy restricts "documents" or scripts from different sources from reading or setting the current "document" certain attributes. (White hat talks about web security [1])

Scripts loaded from one domain are not allowed to access document attributes of another domain.

For example:

For example, a malicious website page embeds a bank’s login page through an iframe (the two are from different sources). If there is no same-origin restriction, the javascript script on the malicious webpage will The username and password can be obtained when the user logs into the bank.

In the browser, tags such as <script>, <img src="/static/imghwm/default1.png" data-src="http://localhost:8081/test2.html" class="lazy" alt="Detailed explanation of JS origin policy + cross-domain access usage" >, <iframe>, <link> can load cross-domain resources without being restricted by the same origin, but are restricted by the browser. The JavaScript permissions are disabled so that it cannot read or write the loaded content. </script>

In addition, the same-origin policy only limits the HTML documents of web pages, and other loaded static resources such as javascript, css, images, etc. are still considered to belong to the same origin.

Code example (http://localhost:8080/ and http://localhost:8081 have different sources due to different ports):

http://localhost:8080/test.html

  <title>test same origin policy</title>
  
    <iframe></iframe>
    <script>
      document.getElementById("test").contentDocument.body.innerHTML = "write somthing";
    </script>
  

http://localhost:8081/test2.html

  <title>test same origin policy</title>
  
    Testing.
  

You will get the following error in Firefox:

Error: Permission denied to access property ' body'

The domain attribute of the Document object stores the host name of the server that loads the document, and you can set it.

For example, pages from "blog.jb51.net" and pages from "bbs.jb51.net" both set document.domain to "jb51.net", then the scripts from the two subdomains can interact with each other. access.

For security reasons, it cannot be set to other main domains. For example, http://www.jb51.net/ cannot be set to sina.com

##2. Ajax cross-domain

Ajax (XMLHttpRequest) requests are restricted by the same-origin policy.

Ajax can interact with remote servers through XMLHttpRequest. In addition, XMLHttpRequest is a pure

Javascript object. This interaction process is performed in the background and is not easily noticed by users.

Therefore, XMLHTTP has actually broken through the original Javascript security restrictions.

For example:

Suppose a website references the javascript of other sites. This site is compromised and added to the javascript to obtain user input and submit it to other sites through ajax, so that the source can be Continuously collect information.

Or maybe a website has a vulnerability that causes XSS to inject a javascript script. This script can obtain user information through ajax and submit it to other sites through ajax, so that information can be collected continuously.

If we want to take advantage of XMLHTTP's refresh-free asynchronous interaction capabilities, but are unwilling to blatantly break through Javascript's security policy, the alternative is to add strict same-origin restrictions to XMLHTTP.

This security policy is very similar to Applet's security policy. The limitation of IFrame is that it cannot access data in cross-domain HTML DOM, while XMLHTTP fundamentally limits the submission of cross-domain requests. (In fact, it is mentioned below that CORS has relaxed restrictions)

With the development of Ajax technology and network services, the requirements for cross-domain are becoming stronger and stronger. The following introduces the cross-domain technology of Ajax.

2.1 JSONP

JSONP技术实际和Ajax没有关系。我们知道<script>标签可以加载跨域的javascript脚本,并且被加载的脚本和当前文档属于同一个域。因此在文档中可以调用/访问脚本中的数据和函数。如果javascript脚本中的数据是动态生成的,那么只要在文档中动态创建<script>标签就可以实现和服务端的数据交互。</script>

JSONP就是利用<script>标签的跨域能力实现跨域数据的访问,请求动态生成的JavaScript脚本同时带一个callback函数名作为参数。其中callback函数本地文档的JavaScript函数,服务器端动态生成的脚本会产生数据,并在代码中以产生的数据为参数调用callback函数。当这段脚本加载到本地文档时,callback函数就被调用。</script>

第一个站点的测试页面(http://localhost:8080/test.html):

<script>
  <script>
    function test_handler(data) {
      console.log(data);
    }
</script>

服务器端的Javascript脚本(http://localhost:8081/test_data.js):

test_handler('{"data": "something"}');

为了动态实现JSONP请求,可以使用Javascript动态插入<script>标签:</script>

<script>
    // this shows dynamic script insertion
    var script = document.createElement(&#39;script&#39;);
    script.setAttribute(&#39;src&#39;, url);
    // load the script
    document.getElementsByTagName(&#39;head&#39;)[0].appendChild(script);
</script>

JSONP协议封装了上述步骤,jQuery中统一是现在AJAX中(其中data type为JSONP):

http://localhost:8080/test?callback=test_handler

为了支持JSONP协议,服务器端必须提供特别的支持[2],另外JSONP只支持GET请求。

2.2 Proxy

使用代理方式跨域更加直接,因为SOP的限制是浏览器实现的。如果请求不是从浏览器发起的,就不存在跨域问题了。

使用本方法跨域步骤如下:

1. 把访问其它域的请求替换为本域的请求

2. 本域的请求是服务器端的动态脚本负责转发实际的请求

各种服务器的Reverse Proxy功能都可以非常方便的实现请求的转发,如Apache httpd + mod_proxy。

Eg.

为了通过Ajax从http://localhost:8080访问http://localhost:8081/api,可以将请求发往http://localhost:8080/api。

然后利用Apache Web服务器的Reverse Proxy功能做如下配置:

ProxyPass /api http://localhost:8081/api

2.3 CORS

2.3.1 Cross origin resource sharing

“Cross-origin resource sharing (CORS) is a mechanism that allows a web page to make XMLHttpRequests to another domain. Such "cross-domain" requests would otherwise be forbidden by web browsers, per the same origin security policy. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request. It is more powerful than only allowing same-origin requests, but it is more secure than simply allowing all such cross-origin requests.” ----Wikipedia[3]

通过在HTTP Header中加入扩展字段,服务器在相应网页头部加入字段表示允许访问的domain和HTTP method,客户端检查自己的域是否在允许列表中,决定是否处理响应。

实现的基础是JavaScript不能够操作HTTP Header。某些浏览器插件实际上是具有这个能力的。

服务器端在HTTP的响应头中加入(页面层次的控制模式):

Access-Control-Allow-Origin: example.com
Access-Control-Request-Method: GET, POST
Access-Control-Allow-Headers: Content-Type, Authorization, Accept, Range, Origin
Access-Control-Expose-Headers: Content-Range
Access-Control-Max-Age: 3600

多个域名之间用逗号分隔,表示对所示域名提供跨域访问权限。"*"表示允许所有域名的跨域访问。

客户端可以有两种行为:

1. 发送OPTIONS请求,请求Access-Control信息。如果自己的域名在允许的访问列表中,则发送真正的请求,否则放弃请求发送。

2. 直接发送请求,然后检查response的Access-Control信息,如果自己的域名在允许的访问列表中,则读取response body,否则放弃。

本质上服务端的response内容已经到达本地,JavaScript决定是否要去读取。

Support: [Javascript Web Applications]
* IE >= 8 (需要安装caveat)
* Firefox >= 3
* Safari 完全支持
* Chrome 完全支持
* Opera 不支持

 2.3.2 测试

测试页面http://localhost:8080/test3.html使用jquery发送Ajax请求。

    <title>testing cross sop</title>
    
      Testing.
      <script></script>
      <script>
        $.ajax({
          url: &#39;http://localhost:8000/hello&#39;,
          success: function(data) {
            alert(data);
          },
          error: function() {
            alert(&#39;error&#39;);
          }
        });
      </script>
    

测试Restful API(http://localhost:8000/hello/{name})使用bottle.py来host。

from bottle import route, run, response
@route('/hello')
def index():
  return 'Hello World.'
run(host='localhost', port=8000)

测试1:

测试正常的跨域请求的行为。

测试结果:

1. 跨域GET请求已经发出,请求header中带有

    Origin    http://localhost:8080

2. 服务器端正确给出response

3. Javascript拒绝读取数据,在firebug中发现reponse为空,并且触发error回调

测试2:

测试支持CORS的服务器的跨域请求行为。

对Restful API做如下改动,在response中加入header:

def index():
  #Add CORS header#
  response.set_header("Access-Control-Allow-Origin", "http://localhost:8080")
  return 'Hello World.'

测试结果:

1. 跨域GET请求已经发出,请求header中带有

Origin    http://localhost:8080

2. 服务器端正确给出response

3. 客户端正常获取数据

测试3:

测试OPTIONS请求获取CORS信息。
对客户端的Ajax请求增加header:

$.ajax({
 url: 'http://localhost:8000/hello',
 headers: {'Content-Type': 'text/html'},
 success: function(data) {
   alert(data);
 },
 error: function() {
   alert('error');
 }
});

对Restful API做如下改动:

@route('/hello', method = ['OPTIONS', 'GET'])
def index():
  if request.method == 'OPTIONS':
    return ''
  return 'Hello World.'

测试结果:

1. Ajax函数会首先发送OPTIONS请求
2. 针对OPTIONS请求服务器
3. 客户端发现没有CORS header后不会发送GET请求

测试4:

增加服务器端对OPTIONS方法的处理。

对Restful API做如下改动:

@route('/hello', method = ['OPTIONS', 'GET'])
def index():
    response.headers['Access-Control-Allow-Origin'] = 'http://localhost:8080'
    response.headers['Access-Control-Allow-Methods'] = 'GET, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type'
    if request.method == 'OPTIONS':
      return ''
    return 'Hello World.'

测试结果:

1. Ajax函数会首先发送OPTIONS请求
2. 针对OPTIONS请求服务器
3. 客户端匹配CORS header中的allow headers and orgin后会正确发送GET请求并获取结果

测试发现,Access-Control-Allow-Headers是必须的。

CORS协议提升了Ajax的跨域能力,但也增加了风险。一旦网站被注入脚本或XSS攻击,将非常方便的获取用户信息并悄悄传递出去。

4. Cookie 同源策略

Cookie中的同源只关注域名,忽略协议和端口。所以https://localhost:8080/和http://localhost:8081/的Cookie是共享的。

5. Flash/SilverLight跨域

浏览器的各种插件也存在跨域需求。通常是通过在服务器配置crossdomain.xml[4],设置本服务允许哪些域名的跨域访问。

客户端会首先请求此文件,如果发现自己的域名在访问列表里,就发起真正的请求,否则不发送请求。

<?xml  version="1.0"?>
  nbsp;cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
  <cross-domain-policy>
  <allow-access-from></allow-access-from>
  <allow-http-request-headers-from></allow-http-request-headers-from>
</cross-domain-policy>

通常crossdomain.xml放置在网站根目录。

6. 总结

互联网的发展催生了跨域访问的需求,各种跨域方法和协议满足了需求但也增加了各种风险。尤其是XSS和CSRF等攻击的盛行也得益于此。

了解这些技术背景有助于在实际项目中熟练应用并规避各种安全风险。

Reference

[1] 白帽子讲Web安全: http://www.jb51.net/books/164067.html
[2] 使用 JSONP 实现跨域通信: http://www.ibm.com/developerworks/cn/web/wa-aj-jsonp1/
[3] Cross-origin resource sharing: http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing
[4] Cross-domain policy for Flash movies: http://kb2.adobe.com/cps/142/tn_14213.html

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

react实现移动端数据输出与显示

node服务器跨域步奏详解

The above is the detailed content of Detailed explanation of JS origin policy + cross-domain access usage. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.