Secure API calls with AJAX and PHP to 3rd party API

t-jam picture t-jam · Feb 23, 2018 · Viewed 9.4k times · Source

I want to make GET, POST & PUT calls to a 3rd party API and display the response on the client side via AJAX. The API calls require a token, but I need to keep that token secret / not in the client-side JS code.

I've seen a few suggestions like this one to have server-side code in the middle that would be queried by the AJAX, and would handle the actual API call. I'm OK working directly with the API from AJAX, but I'm unsure of how to work with a two-step process in order to hide the token from users. My Googling hasn't turned up any pointers on a best-practice method of achieving this.

In my case the server in the middle would be running PHP, so I assume cURL / Guzzle is the straightforward option to make the API calls with the token. The API responses will be JSON.

Can anyone please give me a rough example of how this would be achieved using jQuery.ajax(), to PHP, to the 3rd party API?

Alternatively if there are any quality resources that cover this method in detail, I'd appreciate a link. Equally, if this is a terrible method to use it'd be great to know why.

Edit
Probably worth noting that I want as much flexibility in deploying this as possible; it would be used on multiple sites with unique configurations, so ideally this would be implemented without altering server or hosting account configuration.

Answer

georoot picture georoot · Feb 23, 2018

Because all you want is to add token to http headers, which i am assuming is Authorization a simple way would be to implement a proxy server that makes calls to your api endpoint after adding up those. A sample file for nginx would be

location /apiProxy {
    proxy_pass http://www.apiendPoint.com/;
    proxy_set_header Authorization <secret token>;
}

This is a much more smarter approach rather than writing a program and gets you off with 4 lines of code. Make sure to change your parameters accordingly and add other parameters as needed by api client you are using. The only difference on javascript side would be to use the location url rather than one provided by service which acts as a proxy.

Edit

The configuration for apache would be

NameVirtualHost *
<VirtualHost *>
   <LocationMatch "/apiProxy">
      ProxyPass http://www.apiendPoint.com/
      ProxyPassReverse http://www.apiendPoint.com/
      Header add Authorization "<secret token>"
      RequestHeader set Authorization "<secret token>"   
   </LocationMatch>
</VirtualHost>