How to allow access to API only for own pages?

2019-07-09 04:55发布

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!

1条回答
Bombasti
2楼-- · 2019-07-09 05:40

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.

The flow is not:

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

But rather:

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

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.

查看更多
登录 后发表回答