同源策略

什么是同源策略

同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,所谓同源是指: 协议,域名,端口都相同, 就是同源, 否则就是跨域

例如:http://www.it6666.top:80/index.html

  • 协议: http/https/...
  • 一级域名: it6666.top/itzb.com
  • 二级域名: www/study/edu/...
  • 端口号: 80/3306/...

案例

协议 + 一级域名 + 二级域名 + 端口号都相同, 所以同源

http://www.it6666.top:80/index.html
http://www.it6666.top:80/detail.html

协议不同, 所以不同源, 是跨域

http://www.it6666.top:80/index.html
https://www.it6666.top:80/index.html

一级域名不同, 所以不同源, 是跨域

http://www.it6666.top:80/index.html
http://www.itzb.com:80/index.html

二级域名不同, 所以不同源, 是跨域

http://www.it6666.top:80/index.html
http://edu.it6666.top:80/index.html

端口号不同, 所以不同源, 是跨域

http://www.it6666.top:80/index.html
http://www.it6666.top:8090/index.html

同源策略带来的影响

在同源策略下, 浏览器只允许 Ajax 请求同源的数据, 不允许请求不同源的数据,但在企业开发中, 一般情况下为了提升网页的性能, 网页和数据都是单独存储在不同服务器上的,这时如果再通过 Ajax 请求数据就会拿不到跨域数据

如下我将演示一下同源策略所带来的影响,利用 Apache 当作服务器,在服务器当中添加了一个页面,页面内容如下

index.html 页面当中的 jq 自行切换为你自己的:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>同源策略</title>
    <script src="js/jquery-1.12.4.js"></script>
</head>
<body>
<button class="send">发送请求</button>
<script>
    $('.send').click(function () {
        $.ajax({
            url: "http://127.0.0.1:80/Jquery/19-SameOriginPolicy.php",
            success: function (msg) {
                console.log(msg);
            },
            error: function () {
                console.log("请求失败");
            }
        });
    });
</script>
</body>
</html>

然后在服务器当中编写了 PHP 后端代码,当然逻辑很简单就是返回了一句话,19-SameOriginPolicy.php 内容如下:

<?php
echo 'it6666.top'
?>

然后启动服务器访问 index.html 页面,点击发送请求:

image-20211111225546387

请求之后的结果如下:

image-20211111225707875

那么我们来分析一下如上请求的地址信息:

通过如上的分析可以很轻易的发现,协议,一级,二级,端口号都是同源的,所以不会产生跨域访问的情况,这个时候我们在利用 idea 来启动 index.html 因为 idea 这个软件内部是自带了一个 web 服务器的,启动之后点击发送请求结果如下图所示:

image-20211111230038538

通过上图发现,产生了跨域问题,我们继续来分析一下如上的信息:

通过如上分析了之后可以发现,端口号是不同源的,所以就产生了跨域问题

跨域解决方案

  • jsonp
  • document.domain + iframe
  • location.hash + iframe
  • window.name + iframe
  • window.postMessage
  • flash 等第三方插件

End

posted @ 2021-11-11 00:53  BNTang  阅读(496)  评论(0编辑  收藏  举报