【轉載】基於CodeIgniter框架Restful風格API的Auth驗證

服務端開始準備改形成Restuful風格API.php

舊版本採用if else對請求判斷分發的機制太醜陋,
選用了CodeIgniter框架。git

使用插件:
https://github.com/chriskacerguis/codeigniter-restservergithub

由於使用了CodeIgniter的SAE版本,避免配置破壞,因此只複製插件目錄下的三個文件。框架

config/rest.php
libraries/Format.php
libraries/Rest_Controller.php

根據官方示例編碼本身的RestController。codeigniter

修改Auth配置

使用Digest認證
http://zh.wikipedia.org/wiki/HTTP摘要認證ui

1
2
3
4
5
$config[ 'rest_realm'] = 'REST API'; //定義realm用於加密
$config[ 'rest_auth'] = 'digest'; //切換auth規則方案爲digest
$config[ 'auth_source'] = 'library'; //切換驗證方案爲自定義驗證
$config[ 'auth_library_class'] = 'auth'; //定義用於執行驗證的類名
$config[ 'auth_library_function'] = 'login'; //定義用於驗證的方法明

配置完參數後,該框架講使用libraries文件夾下面的auth類名,經過login方法進行驗證請求是否有效。
login方法必須含有兩個參數
而且在digest認證下,必須返回md5(username:realm:password)組合後的字符串,框架會自行對請求中的參數頭進行驗證是否與該串一致。
例如以下代碼將經過用戶名admin與密碼1234的用戶經過驗證。編碼

<?php
class auth
{
    public function login($username, $password)
    {
        return md5('admin' . ':' . "REST API" . ":1234");
    }
}

 

若是使用Basic認證,只須要將rest_auth配置切換成basic而且在login中返回true、false對應成功與失敗便可。加密

轉載自 http://eyyoung.github.io/2014/12/15/codeigniter-restserver-auth/spa

 

做者 YOUNG Peaceful.插件

相關文章
相關標籤/搜索