且构网

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

如何仅允许对自己页面的 API 访问?

更新时间:2023-12-02 10:08:10

不,这完全不可能.您可以添加令牌以使其更难,在 Javascript 中生成内容等等,但这只会使您的页面变慢并且更容易崩溃.

No, it's completely impossible. You could add tokens to make it harder, generate things in Javascript, etc, etc, but all that would do is make your page slower and more likely to crash.

流程不是:

(1) User --> (2) MyOwnPages --> (3) RestAPI.

而是:

(1) User --> (2) Users Browser --> (3) RestAPI.

而且由于是浏览器调用您的 API,因此没有明智的方法来区分它们之间的区别,cURL、Postman 等.您可以做的任何事情,用户都可以输入,例如 Wireshark 以准确查看正在发送的内容,然后他们可以执行浏览器正在执行的任何操作.

And since it's the browser that's making the call to your API, there's no sensible way to tell the difference between that, cURL, Postman, etc. Anything you can do, the user can put, say, Wireshark in the way to see exactly what is being sent, and from that they can do whatever the browser is doing.

准确了解您为什么要这样做会更有帮助,因为无论您的最终目标是什么,都可能有更好的解决方案.

It would be more helpful to understand exactly why you want to do this, as there is likely to be a better solution for whatever your end goal is.