步骤3:确保API服务器具有APP ID和APP SECRET
目前,API服务器被设置为接受全部API请求。我们将需要将之限制在我们自己的应用上,以确保只有我们自己的前端客户端能够完成API请求。另外,你实际上也可以创建一个系统,其中的用户可以创建他们自己的应用,而那些应用也用用对你的API服务器的访问权,这与Facebook和Twitter的应用的的工作原理类似。
我们从为使用API服务器的用户创建一组id-密码对开始。由于这只是一个Demo,我们可以使用任何随机的、32位字符串。对于APP ID,我们将其设定为APP001。
再次打开index.php文件,然后用下列代码更新之:
- <?php
- // Define path to data folder
- define('DATA_PATH', realpath(dirname(__FILE__).'/data'));
- //Define our id-key pairs
- $applications = array(
- 'APP001' => '28e336ac6c9423d946ba02d19c6a2632', //randomly generated app key
- );
- //include our models
- include_once 'models/TodoItem.php';
- //wrap the whole thing in a try-catch block to catch any wayward exceptions!
- try {
- //*UPDATED*
- //get the encrypted request
- $enc_request = $_REQUEST['enc_request'];
- //get the provided app id
- $app_id = $_REQUEST['app_id'];
- //check first if the app id exists in the list of applications
- if( !isset($applications[$app_id]) ) {
- throw new Exception('Application does not exist!');
- }
- //decrypt the request
- $params = json_decode(trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $applications[$app_id], base64_decode($enc_request), MCRYPT_MODE_ECB)));
- //check if the request is valid by checking if it's an array and looking for the controller and action
- if( $params == false || isset($params->controller) == false || isset($params->action) == false ) {
- throw new Exception('Request is not valid');
- }
- //cast it into an array
- $params = (array) $params;
- ...
- ...
- ...
我们在这里已经完成的实际上是实现一个非常简单的认证我们的前端客户端的方法,它利用了与公共-私有密钥认证相似的系统。基本上,这里给出的就是认证过程的步骤分解:
公钥加密
- 完成一个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服务器的前端客户端了。
PHP之友评论