本文介绍了CORS 是执行跨域 AJAX 请求的安全方式吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了 CORS(跨域资源共享)之后,我不明白它如何提高安全性.如果发送了正确的 ORIGIN 标头,则允许跨域 AJAX 通信.例如,如果我发送

After reading about CORS (Cross-Origin Resource Sharing), I don't understand how it improves security. Cross-Domain AJAX communication is allowed if the correct ORIGIN header is sent. As an example, if I send

来源:http://example.com

服务器检查此域是否在白名单中,如果是,则标头:

The server checks if this domain is in the white list and, if it is, header:

Access-Control-Allow-Origin:[在此处收到 url]

Access-Control-Allow-Origin: [received url here]

连同响应一起发回(这是简单的情况,也有预置请求,但问题是一样的).

is sent back, together with the response (This is the simple case, there are also prefighted requests, but the question is the same).

这真的安全吗?如果有人想接收信息,伪造 ORIGIN 标头似乎是一项非常简单的任务.该标准还表示该策略是在浏览器中强制执行的,如果 Access-Control-Allow-Origin 不正确,则会阻止响应.显然,如果有人试图获取该信息,他不会使用标准浏览器来阻止它.

Is this really secure? If someone wants to receive the information, faking an ORIGIN headers seems like a really trivial task. Also the standard says that the policy is enforced in the browser, blocking the response if Access-Control-Allow-Origin is not correct. Obviously if anyone is trying to get that info, he will not use a standard browser to block it.

推荐答案

您不能在 Web 浏览器中使用 JavaScript 伪造 Origin 标头.CORS 旨在防止这种情况发生.

You can't fake an Origin header with JavaScript in a web browser. CORS is designed to prevent that.

在网络浏览器之外,这无关紧要.它并非旨在阻止人们获取可供公众使用的数据.你不能在没有公众知道的情况下将它暴露给公众.

Outside of a web browser, it doesn't matter. It isn't designed to stop people from getting data that is available to the public. You can't expose it to the public without members of the public getting it.

它是这样设计的:

  • Alice,提供旨在通过 Ajax 访问的 API 的人
  • Bob,一个使用网络浏览器的人
  • Charlie,第三方运营自己的网站

如果 Bob 访问 Charlie 的网站,那么 Charlie 无法将 JS 发送到 Bob 的浏览器,以便从 Alice 的网站获取数据并将其发送给 Charlie.

If Bob visits Charlie's website, then Charlie cannot send JS to Bob's browser so that it fetches data from Alice's website and sends it to Charlie.

如果 Bob 在 Alice 的网站上有一个用户帐户,允许他执行诸如发表评论、删除数据或查看向公众提供的数据等操作,则上述情况变得更加重要 —因为在没有保护的情况下,Charlie 的 JS 可以告诉 Bob 的浏览器在 Bob 的背后执行此操作(然后将结果发送给 Charlie).

The above situation becomes more important if Bob has a user account on Alice's website which allows him to do things like post comments, delete data, or see data that is not available to the general public — since without protection, Charlie's JS could tell Bob's browser to do that behind Bob's back (and then send the results to Charlie).

如果您想阻止未经授权的人查看数据,则需要使用密码、SSL 客户端证书或其他一些基于身份的身份验证/授权方式来保护它.

If you want to stop unauthorized people from seeing the data, then you need to protect it with passwords, SSL client certs or some other means of identity-based authentication/authorization.

这篇关于CORS 是执行跨域 AJAX 请求的安全方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 11:55
查看更多