且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

CORS 是一种安全的跨域 AJAX 请求方式吗?

更新时间:2022-06-05 09:10:45

您不能在 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,一个有网络浏览器的人
  • 查理,运行自己网站的第三方

如果 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.