如何仅允许对自己页面的 API 访问? [英] How to allow access to API only for own pages?

查看:51
本文介绍了如何仅允许对自己页面的 API 访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发提供 REST API 的 Spring Boot Web 应用程序.我的大部分页面(thymeleaf 模板)都使用此 API 与后端通信(使用 AJAX 请求).我已经阅读了不同的方法,例如基本身份验证、OAuth2 等.这些方法描述了用户身份验证,之后用户可以访问 API.但我不希望用户使用浏览器或 REST 客户端直接与我的 API 通信(即 postman chrome 扩展,可以访问浏览器的 cookie,通常存储访问令牌的位置).

我有这样的事情:
(1) 用户 --> (2) MyOwnPages --> (3) RestAPI.

有没有办法阻止直接通信 1-3 ?
我能否以某种方式确定请求是从我的页面发出的(即向每个请求添加某种访问令牌)?有什么最佳做法吗?

谢谢!

I'm developing Spring Boot web application, that provides REST API. Most of my pages(thymeleaf templates) use this API to communicate with back-end(using AJAX requests). I have read about different approaches such as Basic Authentication, OAuth2 etc. These approaches describe user authentication, after which users can access API. But i don't want users to directly communicate with my API, using browser or REST client(i.e. postman chrome extension, that has access to browser's cookies, where access tokens are usually stored).

I have something like this:
(1) User --> (2) MyOwnPages --> (3) RestAPI.

Is there a way to prevent direct communication 1-3 ?
Can i somehow determine that request was made from my pages(i.e. add to each request some sort of access token)? Are there any best practices?

Thanks!

推荐答案

不,这完全不可能.您可以添加令牌以使其更难,在 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.

这篇关于如何仅允许对自己页面的 API 访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆