跨域9种解决方案

谁践踏了优雅 2023-10-11 16:32 93阅读 0赞

什么是跨域

说起跨域,就要知道什么是浏览器同源策略

浏览器同源策略:必须是协议、域名、端口完全一致的才符合同源策略

如果以上三项,有一项不同都涉及到跨域问题


为什么浏览器要设置同源策略呢?

没有同源策略限制的两大危险场景

浏览器是从两个方面去做这个同源策略的,一是针对接口的请求,二是针对Dom的查询。

没有同源策略限制的接口请求

有一个东西叫cookie,一般用于处理登录等场景,目的是让服务端知道是谁发出的这次请求。如果请求了登录接口,服务端验证通过后会在响应头加入Set-Cookie字段,然后下次再发请求的时候,浏览器会自动将cookie附加*HTTP请求的头字段Cookie中,服务端就能知道这个用户已经登录过了。知道了上述之后,来看以下场景:

  1. 你准备去清空购物车,于是打开了某买买买网站,登录成功之后,一看购物车东西这么少,不行,还得多买点,于是继续浏览。
  2. 当你在浏览的过程中,你的好基友给你发了一个链接,一脸yin笑地对你说:“你懂的”,于是你毫不犹豫得打开了。
  3. 你饶有兴致地浏览着某网站,谁知这个网站暗地里做了些不可描述的事情!由于没有同源策略的限制,它向某买买买网站发起了请求!聪明的你一定想到上面的话“服务端验证通过后会在响应头加入Set-Cookie字段,然后下次再发请求的时候,浏览器会自动将cookie附加在HTTP请求的头字段Cookie中”,这么一来,这个不法网站就相当于登录了你的账号,可以为所欲为了!如果这不是一个买买买账号,而是你的银行账号,那……

这就是传说中的CSRF攻击。看了这波CSRF攻击之后,心里有个疑问?即使有了同源策略限制,但cookie是明文的,还不是一样能拿下来。于是看了一些cookie相关的文章,知道了服务端可以设置HttpOnly,使得前端无法操作cookie,如果没有这样的设置,像XSS攻击就可以去获取到cookie;设置secure,则保证在https的加密通信中传输以防截获。

没有同源策略限制的Dom查询

  1. 有一天你刚睡醒,收到一封邮件,说是你的银行账号有风险,赶紧点进www.yinghang.com网站改密码,你果断输入你的账号密码,登录进去看看钱有没有少了。
  2. 睡眼朦胧的你没看清楚,平时访问的银行网站是www.yinhang.com,而现在访问的是www.yinghang.com,这个钓鱼网站做了什么呢?


    // 由于没有同源策略的限制,钓鱼网站可以直接拿到别的网站的Dom
    const iframe = window.frames[‘yinhang’]
    const node = iframe.document.getElementById(‘你输入账号密码的Input’)
    console.log(`拿到了这个${

    1. node},我还拿不到你刚刚输入的账号密码吗`)

由此可以知道,同源策略确实能规避一些危险,但不是说有了同源策略就安全,只是说同源策略是一种浏览器最基本的安全机制,毕竟能提高一点攻击的成本。


跨域解决方案

1、 通过jsonp跨域
2、 document.domain + iframe跨域
3、 location.hash + iframe
4、 window.name + iframe跨域
5、 postMessage跨域
6、 跨域资源共享(CORS)
7、 nginx代理跨域
8、 nodejs中间件代理跨域
9、 WebSocket协议跨域

JSONP跨域

jsonp的原理就是利用<script>标签没有跨域限制,通过<script>标签src属性,发送带有callback参数的GET请求,服务端将接口返回数据拼凑到callback函数中,返回给浏览器,浏览器解析执行,从而前端拿到callback函数返回的数据。

1)原生JS实现:

  1. <script>
  2. var script = document.createElement('script');
  3. script.type = 'text/javascript';
  4. // 传参一个回调函数名给后端,方便后端返回时执行这个在前端定义的回调函数
  5. script.src = 'http://www.domain2.com:8080/login?user=admin&callback=handleCallback';
  6. document.head.appendChild(script);
  7. // 回调执行函数
  8. function handleCallback(res) {
  9. alert(JSON.stringify(res));
  10. }
  11. </script>

服务端返回如下(返回时即执行全局函数):

  1. handleCallback({
  2. "success": true, "user": "admin"})

2)jquery Ajax实现:

  1. $.ajax({
  2. url: 'http://www.domain2.com:8080/login',
  3. type: 'get',
  4. dataType: 'jsonp', // 请求方式为jsonp
  5. jsonpCallback: "handleCallback", // 自定义回调函数名
  6. data: {
  7. }
  8. });

3)Vue axios实现:

  1. this.$http = axios;
  2. this.$http.jsonp('http://www.domain2.com:8080/login', {
  3. params: {
  4. },
  5. jsonp: 'handleCallback'
  6. }).then((res) => {
  7. console.log(res);
  8. })

3)node.js实现:

  1. var querystring = require('querystring');
  2. var http = require('http');
  3. var server = http.createServer();
  4. server.on('request', function(req, res) {
  5. var params = querystring.parse(req.url.split('?')[1]);
  6. var fn = params.callback;
  7. // jsonp返回设置
  8. res.writeHead(200, {
  9. 'Content-Type': 'text/javascript' });
  10. res.write(fn + '(' + JSON.stringify(params) + ')');
  11. res.end();
  12. });
  13. server.listen('8080');
  14. console.log('Server is running at port 8080...');

jsonp 缺点是只能发送 get 请求


跨域资源共享(CORS)

普通跨域请求:只服务端设置Access-Control-Allow-Origin即可,前端无须设置,若要带cookie请求:前后端都需要设置。

需注意的是:由于同源策略的限制,所读取的cookie为跨域请求接口所在域的cookie,而非当前页。如果想实现当前页cookie的写入,可参考下文:七、nginx反向代{过}{滤}理中设置proxy_cookie_domain 和 八、NodeJs中间件代{过}{滤}理中cookieDomainRewrite参数的设置。

目前,所有浏览器都支持该功能(IE8+:IE8/9需要使用XDomainRequest对象来支持CORS)),CORS也已经成为主流的跨域解决方案。

前端设置

1.)原生ajax

  1. // 前端设置是否带cookie
  2. xhr.withCredentials = true;

示例代码:

  1. var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容
  2. // 前端设置是否带cookie
  3. xhr.withCredentials = true;
  4. xhr.open('post', 'http://www.domain2.com:8080/login', true);
  5. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  6. xhr.send('user=admin');
  7. xhr.onreadystatechange = function() {
  8. if (xhr.readyState == 4 && xhr.status == 200) {
  9. alert(xhr.responseText);
  10. }
  11. };

2.)jQuery ajax

  1. $.ajax({
  2. ...
  3. xhrFields: {
  4. withCredentials: true // 前端设置是否带cookie
  5. },
  6. crossDomain: true, // 会让请求头中包含跨域的额外信息,但不会含cookie
  7. ...
  8. });

3.)vue框架

a.) axios设置:

  1. axios.defaults.withCredentials = true

b.) vue-resource设置:

  1. Vue.http.options.credentials = true

服务端设置

若后端设置成功,前端浏览器控制台则不会出现跨域报错信息,反之,说明没设置成功。

1.)Java后台:

  1. /*
  2. * 导入包:import javax.servlet.http.HttpServletResponse;
  3. * 接口参数中定义:HttpServletResponse response
  4. */
  5. // 允许跨域访问的域名:若有端口需写全(协议+域名+端口),若没有端口末尾不用加'/'
  6. response.setHeader("Access-Control-Allow-Origin", "http://www.domain1.com");
  7. // 允许前端带认证cookie:启用此项后,上面的域名不能为'*',必须指定具体的域名,否则浏览器会提示
  8. response.setHeader("Access-Control-Allow-Credentials", "true");
  9. // 提示OPTIONS预检时,后端需要设置的两个常用自定义头
  10. response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With");

2.)Nodejs后台示例:

  1. var http = require('http');
  2. var server = http.createServer();
  3. var qs = require('querystring');
  4. server.on('request', function(req, res) {
  5. var postData = '';
  6. // 数据块接收中
  7. req.addListener('data', function(chunk) {
  8. postData += chunk;
  9. });
  10. // 数据接收完毕
  11. req.addListener('end', function() {
  12. postData = qs.parse(postData);
  13. // 跨域后台设置
  14. res.writeHead(200, {
  15. 'Access-Control-Allow-Credentials': 'true', // 后端允许发送Cookie
  16. 'Access-Control-Allow-Origin': 'http://www.domain1.com', // 允许访问的域(协议+域名+端口)
  17. /*
  18. * 此处设置的cookie还是domain2的而非domain1,因为后端也不能跨域写cookie(nginx反向代{过}{滤}理可以实现),
  19. * 但只要domain2中写入一次cookie认证,后面的跨域接口都能从domain2中获取cookie,从而实现所有的接口都能跨域访问
  20. */
  21. 'Set-Cookie': 'l=a123456;Path=/;Domain=www.domain2.com;HttpOnly' // HttpOnly的作用是让js无法读取cookie
  22. });
  23. res.write(JSON.stringify(postData));
  24. res.end();
  25. });
  26. });
  27. server.listen('8080');
  28. console.log('Server is running at port 8080...');

nginx代理跨域

通过Nginx配置一个代理服务器域名与domain1相同,端口不同)做跳板机,反向代理访问domain2接口,并且可以顺便修改cookie中domain信息,方便当前域cookie写入,实现跨域访问。

nginx具体配置:

  1. #proxy服务器
  2. server {
  3. listen 81;
  4. server_name www.domain1.com;
  5. location / {
  6. proxy_pass http://www.domain2.com:8080; #反向代理
  7. proxy_cookie_domain www.domain2.com www.domain1.com; #修改cookie里域名
  8. index index.html index.htm;
  9. # 当用webpack-dev-server等中间件代理接口访问nignx时,此时无浏览器参与,故没有同源限制,下面的跨域配置可不启用
  10. add_header Access-Control-Allow-Origin http://www.domain1.com; #当前端只跨域不带cookie时,可为*
  11. add_header Access-Control-Allow-Credentials true;
  12. }
  13. }

NodeJS中间件代理跨域

node中间件实现跨域代理,原理大致与nginx相同,都是通过启一个代理服务器,实现数据的转发,也可以通过设置cookieDomainRewrite参数修改响应头中cookie中域名,实现当前域的cookie写入,方便接口登录认证。

非vue框架的跨域(2次跨域)

利用node + express + http-proxy-middleware搭建一个proxy服务器。

1.)前端代码示例:

  1. var xhr = new XMLHttpRequest();
  2. // 前端开关:浏览器是否读写cookie
  3. xhr.withCredentials = true;
  4. // 访问http-proxy-middleware代{过}{滤}理服务器
  5. xhr.open('get', 'http://www.domain1.com:3000/login?user=admin', true);
  6. xhr.send();

2.)中间件服务器:

  1. var express = require('express');
  2. var proxy = require('http-proxy-middleware');
  3. var app = express();
  4. app.use('/', proxy({
  5. // 代{过}{滤}理跨域目标接口
  6. target: 'http://www.domain2.com:8080',
  7. changeOrigin: true,
  8. // 修改响应头信息,实现跨域并允许带cookie
  9. onProxyRes: function(proxyRes, req, res) {
  10. res.header('Access-Control-Allow-Origin', 'http://www.domain1.com');
  11. res.header('Access-Control-Allow-Credentials', 'true');
  12. },
  13. // 修改响应信息中的cookie域名
  14. cookieDomainRewrite: 'www.domain1.com' // 可以为false,表示不修改
  15. }));
  16. app.listen(3000);
  17. console.log('Proxy server is listen at port 3000...');

vue框架的跨域(1次跨域)

利用node + webpack + webpack-dev-server代{过}{滤}理接口跨域。在开发环境下,由于vue渲染服务和接口代{过}{滤}理服务都是webpack-dev-server同一个,所以页面与代理接口之间不再跨域,无须设置headers跨域信息了。

webpack.config.js部分配置:

  1. module.exports = {
  2. entry: {
  3. },
  4. module: {
  5. },
  6. ...
  7. devServer: {
  8. historyApiFallback: true,
  9. proxy: [{
  10. context: '/login',
  11. target: 'http://www.domain2.com:8080', // 代{过}{滤}理跨域目标接口
  12. changeOrigin: true,
  13. secure: false, // 当代{过}{滤}理某些https服务报错时用
  14. cookieDomainRewrite: 'www.domain1.com' // 可以为false,表示不修改
  15. }],
  16. noInfo: true
  17. }
  18. }

document.domain + iframe跨域

此方案仅限主域相同,子域不同的跨域应用场景。

实现原理:两个页面都通过js强制设置document.domain为基础主域,就实现了同域。

a. 父窗口:(http://www.domain.com/a.html)

  1. <iframe id="iframe" src="http://child.domain.com/b.html"></iframe>
  2. <script>
  3. document.domain = 'domain.com';
  4. var user = 'admin';
  5. </script>

b. 子窗口:http://child.domain.com/b.html

  1. <script>
  2. document.domain = 'domain.com';
  3. // 获取父窗口中变量
  4. alert('get js data from parent ---> ' + window.parent.user);
  5. </script>

location.hash + iframe跨域

实现原理:a欲与b跨域相互通信,通过中间页c来实现。三个页面,不同域之间利用iframe的location.hash传值,相同域之间直接js访问来通信。

具体实现:A域:a.html -> B域:b.html -> A域:c.html,a与b不同域只能通过hash值单向通信,b与c也不同域也只能单向通信,但c与a同域,所以c可通过parent.parent访问a页面所有对象。

1)a.html:(http://www.domain1.com/a.html)

  1. <iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
  2. <script>
  3. var iframe = document.getElementById('iframe');
  4. // 向b.html传hash值
  5. setTimeout(function() {
  6. iframe.src = iframe.src + '#user=admin';
  7. }, 1000);
  8. // 开放给同域c.html的回调方法
  9. function onCallback(res) {
  10. alert('data from c.html ---> ' + res);
  11. }
  12. </script>

2)b.html:(http://www.domain2.com/b.html)

  1. <iframe id="iframe" src="http://www.domain1.com/c.html" style="display:none;"></iframe>
  2. <script>
  3. var iframe = document.getElementById('iframe');
  4. // 监听a.html传来的hash值,再传给c.html
  5. window.onhashchange = function () {
  6. iframe.src = iframe.src + location.hash;
  7. };
  8. </script>

3)c.html:(http://www.domain1.com/c.html)

  1. <script>
  2. // 监听b.html传来的hash值
  3. window.onhashchange = function () {
  4. // 再通过操作同域a.html的js回调,将结果传回
  5. window.parent.parent.onCallback('hello: ' + location.hash.replace('#user=', ''));
  6. };
  7. </script>

window.name + iframe跨域

window.name属性的独特之处:name值在不同页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的name值(2MB)。

1)html:(http://www.domain1.com/a.html)

  1. var proxy = function(url, callback) {
  2. var state = 0;
  3. var iframe = document.createElement('iframe');
  4. // 加载跨域页面
  5. iframe.src = url;
  6. // onload事件会触发2次,第1次加载跨域页,并留存数据于window.name
  7. iframe.onload = function() {
  8. if (state === 1) {
  9. // 第2次onload(同域proxy页)成功后,读取同域window.name中数据
  10. callback(iframe.contentWindow.name);
  11. destoryFrame();
  12. } else if (state === 0) {
  13. // 第1次onload(跨域页)成功后,切换到同域代{过}{滤}理页面
  14. iframe.contentWindow.location = 'http://www.domain1.com/proxy.html';
  15. state = 1;
  16. }
  17. };
  18. document.body.appendChild(iframe);
  19. // 获取数据以后销毁这个iframe,释放内存;这也保证了安全(不被其他域frame js访问)
  20. function destoryFrame() {
  21. iframe.contentWindow.document.write('');
  22. iframe.contentWindow.close();
  23. document.body.removeChild(iframe);
  24. }
  25. };
  26. // 请求跨域b页面数据
  27. proxy('http://www.domain2.com/b.html', function(data){
  28. alert(data);
  29. });

2)proxy.html:(http://www.domain1.com/proxy.html)

中间代理页,与a.html同域,内容为空即可。

3)html:(http;//www.domain2.com/b.html)

  1. <script>
  2. window.name = 'This is domain2 data!';
  3. </script>

通过iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name从外域传递到本地域。这个就巧妙地绕过了浏览器的跨域访问限制,但同时它又是安全操作。


postMessage跨域

postMessage是HTML5 XMLHttpRequest Level 2中的API,且是为数不多可以跨域操作的window属性之一,它可用于解决以下方面的问题:

a.) 页面和其打开的新窗口的数据传递
b.) 多窗口之间消息传递
c.) 页面与嵌套的 iframe 消息传递
d.) 上面三个场景的跨域数据传递

用法:postMessage(data,origin)方法接受两个参数:

  • data:html5规范支持任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用JSON.stringify()序列化。
  • origin:协议+主机+端口号,也可以设置为”*“,表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为”/“。

1.)a.html:(http://www.domain1.com/a.html)

  1. <iframe id="iframe" src="http://www.domain2.com/b.html" style="display:none;"></iframe>
  2. <script>
  3. var iframe = document.getElementById('iframe');
  4. iframe.onload = function() {
  5. var data = {
  6. name: 'aym'
  7. };
  8. // 向domain2传送跨域数据
  9. iframe.contentWindow.postMessage(JSON.stringify(data), 'http://www.domain2.com');
  10. };
  11. // 接受domain2返回数据
  12. window.addEventListener('message', function(e) {
  13. alert('data from domain2 ---> ' + e.data);
  14. }, false);
  15. </script>

2.)b.html:(http://www.domain2.com/b.html)

  1. <script>
  2. // 接收domain1的数据
  3. window.addEventListener('message', function(e) {
  4. alert('data from domain1 ---> ' + e.data);
  5. var data = JSON.parse(e.data);
  6. if (data) {
  7. data.number = 16;
  8. // 处理后再发回domain1
  9. window.parent.postMessage(JSON.stringify(data), 'http://www.domain1.com');
  10. }
  11. }, false);
  12. </script>

WebSocket协议跨域

WebSocket protocol是HTML5一种新的协议。它实现了浏览器与服务器全双工通信,同时允许跨域通讯,是server push技术的一种很好的实现。

原生WebSocket API使用起来不太方便,我们使用Socket.io,它很好地封装了webSocket接口,提供了更简单、灵活的接口,也对不支持webSocket的浏览器提供了向下兼容。

1.)前端代码:

  1. <div>user input:<input type="text"></div>
  2. <script src="./socket.io.js"></script>
  3. <script>
  4. var socket = io('http://www.domain2.com:8080');
  5. // 连接成功处理
  6. socket.on('connect', function() {
  7. // 监听服务端消息
  8. socket.on('message', function(msg) {
  9. console.log('data from server: ---> ' + msg);
  10. });
  11. // 监听服务端关闭
  12. socket.on('disconnect', function() {
  13. console.log('Server socket has closed.');
  14. });
  15. });
  16. document.getElementsByTagName('input')[0].onblur = function() {
  17. socket.send(this.value);
  18. };
  19. </script>

2.)Nodejs socket后台:

  1. var http = require('http');
  2. var socket = require('socket.io');
  3. // 启http服务
  4. var server = http.createServer(function(req, res) {
  5. res.writeHead(200, {
  6. 'Content-type': 'text/html'
  7. });
  8. res.end();
  9. });
  10. server.listen('8080');
  11. console.log('Server is running at port 8080...');
  12. // 监听socket连接
  13. socket.listen(server).on('connection', function(client) {
  14. // 接收信息
  15. client.on('message', function(msg) {
  16. client.send('hello:' + msg);
  17. console.log('data from client: ---> ' + msg);
  18. });
  19. // 断开处理
  20. client.on('disconnect', function() {
  21. console.log('Client socket has closed.');
  22. });
  23. });

发表评论

表情:
评论列表 (有 0 条评论,93人围观)

还没有评论,来说两句吧...

相关阅读

    相关 9解决方案

    什么是跨域 说起跨域,就要知道什么是浏览器同源策略 浏览器同源策略:必须是协议、域名、端口完全一致的才符合同源策略 如果以上三项,有一项不同都涉及到跨域问题 ---