0

Currently I am using AJAX to request a simple JSON response from an external API. The problem is, that the API key is exposed. I'm aware the best method is to process this through admin-ajax and set call the url through PHP. What is the most secure method to do this, and how can this be requested through PHP?

$.ajax({
  type: "GET",
  url: "https://link.to/api/v2/link?time=day&key=(APIKEYHERE)&response_type=json",
  data: dataString,
  dataType: "json",

  //if received a response from the server
  success: function(response) {
      console.log(response);
  }, 
});
4

I would break this problem in to 2 parts.

First, you could sent an Ajax request to your server, sending only the dataString variable.

Then, you can use either cURL or wp_remote_get() on the server to access the real API.

This could be the only solution, if you want to avoid playing hide and seek with hashes and writing tons of code just to make it hard for the users to find the API key.

  • Thanks Jack! I did indeed end up doing it through AJAX and using cURL to gather the data. Didn't know about wp_remote_get(). Are there any benefits to using this over standard cURL? – scopeak Mar 18 '18 at 9:18
  • You're welcome. Well, it's easier to use though, a more WordPressy way to do it! – Jack Johansson Mar 18 '18 at 9:25
0

It depends on what the external API offers, basically read/write access to some data.
I think:

  • If your website visitor is allowed those access/permissions on that data, it is ok.
  • If your website visitor is not allowed those access/permissions on that data, it is not ok.

Think of Google and Facebook, they provide app and user api keys.
That will depends on your use case.
But i can say that if the external API data access is sensible you should do that on the server and go throw AJAX or REST.

  • Good points! I was thinking this too. I do want the user to be able to filter the data parameters of the url so maybe this will be okay. As it's my own external API, I don't want users to use this URL outside the site. Maybe I should look into restricting API requests to the server IP only. – scopeak Mar 17 '18 at 17:47
  • Look at what other API providers do. They’ll typically limit the number of transactions a key is allowed to perform, and let the user restrict their key to use on a particular domain/server IP. – Jacob Peattie Mar 17 '18 at 19:46
  • Yeah. I ended up just doing it through a proxy by sending the form fields via ajax to a php function and returning results. Not as quick but much more secure :) Thanks! – scopeak Mar 17 '18 at 20:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.