2017-05-28 60 views
0

我已經嘗試創建一個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); 

請不要有什麼建議可能是錯在這裏去。

+1

你在做什麼和JWT(JSON Web Token)是一樣的概念。有很多這個https://github.com/firebase/php-jwt的館藏,也許你應該看看他們 – Treast

+0

@Treast ..其實我從JWT得到了這個想法,並決定做類似的事情。這似乎很安全。謝謝你,我會看看這個..:D –

回答

1

我有類似的問題,並發現如果令牌作爲查詢字符串參數傳遞幷包含+字符它將被刪除。我發現這個問題,因爲電話並不總是打破。對我來說最簡單的解決方案是用「P」替換「+」。 AJAX POST and Plus Sign (+) — How to Encode?

+0

其實我使用encodeURI()和decodeURI()爲js部分和encodeurl()和decodeurl()爲php部分,我現在正在成功登錄,雖然我不確定如果再次出現'+',它是否會中斷。謝謝你的方式。 :) –

+0

我碰到與.Net的問題,而不是PHP。儘管編碼和解碼仍然存在,但如果它對您有用,那肯定是更清潔的方法。 –

+0

我已經使它的工作,雖然它有點亂,顯然,我不得不添加urlencode()每次我傳遞從jquery的令牌,無論該令牌是否已編碼或不。 –