php - Securing an API with shared secret -
i'm starting rest api, , have begun researching hashing , shared salts/secrets. have been able generate sha256 hash, sent server via json , matched stored hash.
thats great , all, i'm thinking, ive done json, actual hash generated still visible wants it. under impression these hashes changed everytime re-hashed string using hash_hmac.
so how make sure random user wont find little json snippet, grap hashed key , start making api calls?
i might have misunderstood concept completely, bumps appreciated.
heres "client" page:
<?php $key= hash_hmac('sha256', '66c74620db28603fe4bec7b0f3a8e53b', 'gwerganaevawe21_3faseghbamoirvqwd'); ?> <script> $.getjson( "domain.com/api/publiccoursesession.php?key=<?php echo $key;?>", function( data ) { $.each( data, function( key, val ) { console.log(val); }); }); </script>
and here publiccoursesession.php:
header("content-type: application/json"); header('access-control-allow-origin: *'); $apikey =$_get['key']; session_start(); function hash_compare($a, $b) { if (!is_string($a) || !is_string($b)) { return false; } $len = strlen($a); if ($len !== strlen($b)) { return false; } $status = 0; ($i = 0; $i < $len; $i++) { $status |= ord($a[$i]) ^ ord($b[$i]); } return $status === 0; } $currentnetwork = getcurrentnetwork(); $currentkey = getnetworkapikey(getnetworkid($currentnetwork)); $currentsecret = getnetworkapisecret(getnetworkid($currentnetwork)); $currentkey= hash_hmac('sha256', $currentkey, $currentsecret); if (hash_compare($apikey,$currentkey)) { $status='correct'; } else { $status='not correct'; } $arr[] = ["key"=>$apikey, "currentkey"=>$currentkey, "correctkeys"=>$status]; echo json_encode($arr);
you did well, that's step 1.
thing is, can't security on browser - should providing user secret key once authenticates himself using credentials (like username/password). once has secret key can use authenticate requests , no longer needs send username/password , forth across interwebs..
goal of secret key simplify authenticated requests once user started session. start session need authenticate first though, otherwise you'll providing secret key defeats purpose.
also, key should generated per user , expire after x amount of time can't used indefinitely.
hope helps!