Restricting access to REST API

2019-05-23 14:14发布

问题:

I'm making a PHP backend for my application using REST API.

I would like to prevent other's script to access my API. I thought of using $_SERVER['HTTP_REFERER'] to avoid them. But, in what situation does the HTTP_REFERER not work?, says we cant rely on that.

Is there any other way to restrict my API to only my client?

回答1:

So, you can implement HTTP basic authentication, as suggested by Marcin. Or, you can implement OAuth as suggsted by HQarroum. The former is much easier to implement. For HTTP BASIC, requests from your client look like this:

.. https://username:password@yourbackend.host.com/resource/method/foo/bar ..

Implementing HTTP basic auth is very simple. In Apache, see this. For nginx, see this.

Regarding OAuth, that's a bit more complex of an implementation. If you are looking into OAuth, and you don't have the need for different scopes (levels of authorization to access different levels of data), then you should implement a two-legged OAuth flow. However, I do believe that OAuth may be overkill if you're the only consumer of the protected resources.

I recommend using SSL (https) in all cases.

Regards,
Neil
http://developer.mashery.com



回答2:

You could just use ordinary HTTP user/pass authentication.



回答3:

You should look at the OAuth protocol and implement it for the clients using your API.