简体   繁体   中英

How can I make sure that my PHP api can only be used by a specific javascript page

I have a PHP page ("An API") that does server-side stuff (eg entering info into a database) based on GET string input.

Would it be possible for me to secure it so that only the JavaScript code on a specific site can access the api, including securing it against, for example, someone typing into a JavaScript console while on the site?

No, it is impossible to completely protect against that.

You may, however, make it more difficult. For example:

  • Require the Referer header to point to that page (some browsers don't send Referer , however)
  • You could also check for X-Requested-With being equal to XMLHttpRequest if the JS library you're using sets that.

You can, but only partially. For example Google uses a method of API keys that are matched against $_SERVER["HTTP REFERER"], but these things can easily be forged. Just make sure that a user will need real authentication for things that need real security (updates/edits/deletes etc.)

Quite simply if you are exposing a page to the public treat the input as untrusted. Asking users politely not look at the key doesn't work. Always validate whatever input you get against the credentials of the user.

I would use an established method (not a roll your own) to login with the credentials of the user and validate the input on the server side. There is no way on the client end to force the users not to take specific actions (say, calling your page or * cough * copy a music file * cough *). This technology would be called DRM or something similar

Another issue is that you are using GET requests to permanently alter state on the server. Don't do that: use a POST (or PUT or DELETE) request instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM