简体   繁体   中英

How to hide my API key between PHP and Javascript?

This is a challenge I am facing in Reactjs, though I don't believe that it is necessarily attributed to it. I am trying to make an API call in React. And while it works, the code also reveals my API key, which below is indicated by my javascript variable sting . When I preview the code in my browser, sting quite clearly shows my API key.

render: function() {
    if (this.state.trial) {
      return this.iftroo();
    }
  } 
});

var Troo = React.createClass({
render: function() {
  var sting = "<?php
  $con = mysqli_connect('localhost', 'root', '', 'worldly') or die("Trying");
  $query = "select * from testi";
  $result = mysqli_query($con, $query);
  while($row = mysqli_fetch_array($result)){
  echo $row["userName"];}
  ?>";  
  var weather = new XMLHttpRequest();
  weather.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=imperial&appid="+sting, false);
  weather.send(null);
  var r = JSON.parse(weather.response);
  var tempurature = r.main.temp;

  return (
    <p>
      {tempurature}
    </p>

I understand that in order to get this to work, I will likely have to embed my javascript code inside my PHP. However, doing so leads to errors, such as PHP not recognizing javascript var characters.

What measures can I take to hide my API keys from the browser?

If you want to hide the API key from the browser then you must simply never give it to the browser .

You can't use the API key from client side JavaScript and keep it hidden from the client.

Make any HTTP request that needs to use it from your server (eg using PHP's cURL library).

You could generate one-time jwt api keys, for a special user, with expiration time, and what ever information assigned it.

edit

OK, now I see, that the api key is for an external service. Don't know how the policy for the weather service is, but.. I think this is not the right way to go, you should make this request on the server.

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