我已經嘗試創建一個RESTful API服務。我通過將成功登錄時登錄腳本返回的字符串(使用存儲在數據庫中的隨機生成的密鑰)進行哈希生成令牌,作爲JSON對象的一部分發送到客戶端。客戶端將令牌(以及其他一些字段作爲JSON對象)作爲GET/POST參數傳遞,以訪問其他API服務。但是,似乎當令牌字符串作爲JSON對象傳遞時,字符串會在中間的某個位置被更改,並且在驗證端點處使用密鑰對其進行反向散列並不會產生與被散列的字符串相同的字符串。結果是獲取由令牌保護的數據的不成功嘗試。發送哈希令牌作爲GET參數
我加入是相關的部分代碼:
登錄腳本
$secret = newsecret($rand);
$token = newtoken($secret, $str);
$qry1 = "UPDATE user_master set user_secret='".$secret."' where user_code='".$uid."'";
$res1 = mysqli_query($conn, $qry1);
$outdata = array("status" => "success", "username" => $un, "uid" => $uid, "token" => $token);
header('Content-type: application/json');
echo json_encode($outdata);
客戶端JS
$.post("http://www.ckoysolutions.com/apis/login.php", inputs).done(function(data){
if(data.status=="success") {
var inputs = '{ '
+'"uid" : "'+data.uid+'" , '
+'"token" : "'+data.token+'"'
+' }';
window.location='http://hasconpanel.ckoysolutions.com/hasconpanel.php?inputs='+inputs;
}
else {
alert(data.message);
}
});
重定向頁面(http://hasconpanel.ckoysolutions.com/hasconpanel.php)發送令牌json作爲一個curl postfield for在http://www.ckoysolutions.com/apis/authuser.php用於驗證
if(isset($inputs->uid) && isset($inputs->token)) {
$token = $inputs->token;
$uid = $inputs->uid;
$auth_data = array("uid" => $uid, "token" => $token);
$auth_json = json_encode($auth_data);
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $auth_json,
CURLOPT_URL => "http://www.ckoysolutions.com/apis/authuser.php",
CURLOPT_HTTPHEADER => [
'Content-Type: application/json'
]
]);
$result = curl_exec($curl);
curl_close($curl);
echo $result;
}
功能驗證
$row = mysqli_fetch_array($res);
$secret = $row['user_secret'];
$token = $token;
$un = $row['user_name'];
$words = explode(" ",$un);
$fn = $words[0];
$udetails = $row['user_log'];
$udetails = json_decode($udetails);
$uip = $udetails->ip;
$date_time = $udetails->time;
$str = $date_time.$fn.$uip;
$chkstr = decrypt($secret, $token);
if($str == $chkstr) {
$outdata = array("status" => "success");
mysqli_close($conn);
}
else {
$outdata = array("status" => "failure");
mysqli_close($conn);
}
header('Content-type: application/json');
echo json_encode($outdata);
請不要有什麼建議可能是錯在這裏去。
你在做什麼和JWT(JSON Web Token)是一樣的概念。有很多這個https://github.com/firebase/php-jwt的館藏,也許你應該看看他們 – Treast
@Treast ..其實我從JWT得到了這個想法,並決定做類似的事情。這似乎很安全。謝謝你,我會看看這個..:D –