Prevent direct api access from browser

2020-04-21 04:52发布

问题:

Currently as it stands, if a user reads the source of my web application, they'd be able to determine the direct URIs of all the RESTful services my web application utilizes.

The problem I see is this: My web application knows how to correctly use the API, and I might not have thought of every single validation known to man to prevent bad data from being sent through the API.

And so with that is there a method to prevent "direct" access to the API and limit it only to my web application?

P.S. As an FYI: API calls concerning a user are protected by the presence of a user-specific cookie which is only issued upon login. This means I'm not too afraid of User X being able to directly modify User Y's data through the API.

回答1:

No.

If the browser is making the request, the user can spoof the request. Period.

My web application knows how to correctly use the API

That's good, but that's leading you down the path of assuming client-side functionality executed as intended. Never make that assumption.

I might not have thought of every single validation known to man to prevent bad data from being sent through the API

This statement leads me to believe that the API itself is more complex than it needs to be. The best thing you can do is simplify. It's difficult to be more specific without seeing specific code, but API requests should be fairly simple and straightforward and the same techniques to prevent malicious code from getting through should be applied universally. The same general rules apply here as in any web application interaction...

  1. Never trust anything that came from the client
  2. Never assume client-side code executed as intended
  3. Never execute input as code, always treat it as a raw value
  4. and so on...

As you mention toward the end, you've already taken care of authentication and authorization for the requests. Given that, if User X is permitted to make a given API call, then what you're essentially asking is, "How do I allow User X to make an API call without allowing User X to make an API call?" The server can't tell the difference. A request is a request.

Sure, there are things you can try, such as always including some custom header in requests made from code. But anybody can inspect that request and spoof that header. The user's browser isn't part of your application and isn't under your control.



标签: rest