title: How to secure a small php api with public and private key
body: <p>I'm trying to design a small api however I'm a bit stuck on how to secure the api. I have read some articles about how to do this one of them is: Login and retrieving an apikey and then hash some values with this apikey and send the hashed string back along with the request, so it can be done again on server level.</p>
  
  <p>Is this a good way or is this dangerous to do? </p>
  
  <p>If not miss understood, to avoid man in the middle I can add the request url to the variables that will be hashed, or isn't that the appropriate way</p>
  
  <p>Also my brain is stuck on how to use a time stamp to avoid making lots of request to the same url with same data. </p>
  
  <p>I'm sorry if my question have been asked a 1000 times. However I have read some articles now and it's still not clear to me what way to go for my small api.</p>
  
  <p>From what I have read and understand from it this should be the way.</p>
  
  <ol>
  <li>public key is stored in the application to let the user or application login.</li>
  <li>server creates private key for this particular user when it's accessed. Or should this be always the same or a static value that has been created by a person?</li>
  <li>user makes request sends along with the request a signature that's hash_hmac(some values+private key);</li>
  <li>server checks if these value's are correct and does by creating the same hash from the value's that are send.</li>
  <li>If server generates the same hash, the request is valid and can then be executed.</li>
  <li>Is this they way to go or am I missing some mayor things here.</li>
  </ol>
  
  <p>For hasing the data is the underneath way a good way to create a hash?</p>
  
  <pre><code>$l_sPrivateKey = 'something returned by database when user loged in';
  $l_aData = array();
  
  foreach($_POST as $key =&gt; $value){
   if($key == 'signature') continue;
   $l_aData[$key] = $value;
  }
  
  //This should then be the same as $_POST['signature'];
  hash_hmac('sha256',serialize($l_aData),$l_sPrivateKey, false); 
  </code></pre>
  
  <p>Your input would be appreciated.
  Kind regards and thanks in advance</p>