Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

rest - Prevent direct api access from browser

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...