PHP头条
热点:

步骤3:确保API服务器具有APP ID和APP SECRET

目前,API服务器被设置为接受全部API请求。我们将需要将之限制在我们自己的应用上,以确保只有我们自己的前端客户端能够完成API请求。另外,你实际上也可以创建一个系统,其中的用户可以创建他们自己的应用,而那些应用也用用对你的API服务器的访问权,这与Facebook和Twitter的应用的的工作原理类似。

我们从为使用API服务器的用户创建一组id-密码对开始。由于这只是一个Demo,我们可以使用任何随机的、32位字符串。对于APP ID,我们将其设定为APP001

再次打开index.php文件,然后用下列代码更新之:

  1. <?php  
  2. // Define path to data folder  
  3. define('DATA_PATH'realpath(dirname(__FILE__).'/data'));  
  4.  
  5. //Define our id-key pairs  
  6. $applications = array(  
  7.     'APP001' => '28e336ac6c9423d946ba02d19c6a2632'//randomly generated app key   
  8. );  
  9. //include our models  
  10. include_once 'models/TodoItem.php';  
  11.  
  12. //wrap the whole thing in a try-catch block to catch any wayward exceptions!  
  13. try {  
  14.     //*UPDATED*  
  15.     //get the encrypted request  
  16.     $enc_request = $_REQUEST['enc_request'];  
  17.       
  18.     //get the provided app id  
  19.     $app_id = $_REQUEST['app_id'];  
  20.       
  21.     //check first if the app id exists in the list of applications  
  22.     if( !isset($applications[$app_id]) ) {  
  23.         throw new Exception('Application does not exist!');  
  24.     }  
  25.       
  26.     //decrypt the request  
  27.     $params = json_decode(trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $applications[$app_id], base64_decode($enc_request), MCRYPT_MODE_ECB)));  
  28.       
  29.     //check if the request is valid by checking if it's an array and looking for the controller and action  
  30.     if$params == false || isset($params->controller) == false || isset($params->action) == false ) {  
  31.         throw new Exception('Request is not valid');  
  32.     }  
  33.       
  34.     //cast it into an array  
  35.     $params = (array$params;  
  36.     ...  
  37.     ...  
  38.     ...  

我们在这里已经完成的实际上是实现一个非常简单的认证我们的前端客户端的方法,它利用了与公共-私有密钥认证相似的系统。基本上,这里给出的就是认证过程的步骤分解:

 
公钥加密

  • 完成一个API调用,其中提供了$app_id$enc_request
  • $enc_request的值是API调用的参数,利用APP KEY进行加密。APP KEY绝对不会被发送到服务器,它只是被用来散列请求。此外,该请求只能利用APP KEY被解密
  • 一旦API调用到达API服务器,它会查验它自己的应用列表是否与APP ID所提供的一致
  • 当调用被发现,API服务器尝试利用与APP ID发送的密钥相匹配的密钥进行解密
  • 如果请求被解密成功,那么继续执行程序

既然API服务器已经确保具有APP ID和APP SECRET,那么我们就可以开始编写使用API服务器的前端客户端了。


www.phpzy.comtrue/php/20947.htmlTechArticle步骤3:确保API服务器具有APP ID和APP SECRET 目前,API服务器被设置为接受 全部 API请求。我们将需要将之限制在我们自己的应用上,以确保只有我们自己的前...

相关文章

PHP之友评论

今天推荐