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

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

问题描述

我正在开发提供REST API的Spring Boot Web应用程序.我的大多数页面(thymeleaf模板)都使用此API与后端通信(使用AJAX请求).我已经阅读了不同的方法,例如基本身份验证,OAuth2等.这些方法描述了用户身份验证,之后用户可以访问API.但是我不希望用户使用浏览器或REST客户端直接与我的API通信(即邮递员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等.您可以执行任何操作,用户可以输入

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天全站免登陆