codeigniter rest服务器库中基于令牌的身份验证

时间:2017-04-14 06:58:31

标签: php codeigniter-3 codeigniter-restserver

我尝试使用Phil Sturgeon的rest server

codeigniter中构建restful API

问题是我无法弄清楚如何进行基于令牌的身份验证。我正在为移动应用程序构建该API,它是通过HTTPS构建的。首先,用户将通过登录进行身份验证,然后他将能够使用应用程序功能。 我想按照这里解释的方式实施:How token-based authentication works

问题:

如果我在请求中向服务器发送令牌,我应该在哪里检查有效性?
休息服务器库是否支持基于令牌的身份验证? 如果它确实需要做哪些配置?或者我需要实现我的身份验证方法?

还是有更好/更简单的身份验证方式而不是基于令牌?

2 个答案:

答案 0 :(得分:4)

它不支持令牌身份验证。这是我添加它的修改。 REST_Controller.php 搜索“switch($ rest_auth){”add将此案例添加到其中:

        case 'token':
            $this->_check_token();
            break;

然后添加此功能:

/** Check to see if the user is logged in with a token
 * @access protected
 */
protected function _check_token () {
    if (!empty($this->_args[$this->config->item('rest_token_name')])
            && $row = $this->rest->db->where('token', $this->_args[$this->config->item('rest_token_name')])->get($this->config->item('rest_tokens_table'))->row()) {
        $this->api_token = $row;
    } else {
        $this->response([
                $this->config->item('rest_status_field_name') => FALSE,
                $this->config->item('rest_message_field_name') => $this->lang->line('text_rest_unauthorized')
                ], self::HTTP_UNAUTHORIZED);
    }
}   

配置/ rest.php

    // *** Tokens ***
/* Default table schema:
 * CREATE TABLE `api_tokens` (
    `api_token_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `token` VARCHAR(50) NOT NULL,
    `created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (`api_token_id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
 */
$config['rest_token_name'] = 'X-Auth-Token';
$config['rest_tokens_table'] = 'api_tokens';

答案 1 :(得分:2)

获取令牌的控制器:

我构建了一个休息控制器来获取令牌。

require APPPATH . 'libraries/REST_Controller.php';
class Token extends REST_Controller {
    /** 
     * @response array
     */
    public function index_get() {
        $data = $this->Api_model->create_token($this->api_customer_id);

        // ***** Response ******
        $http_code = $data['http_code'];
        unset($data['http_code']);
        $this->response($data, $http_code);
    }
}

令牌模型中的功能:

/** Creates a new token
* @param type $in
* @return type
*/
function create_token ($customer_id) {
    $this->load->database();

    // ***** Generate Token *****
    $char = "bcdfghjkmnpqrstvzBCDFGHJKLMNPQRSTVWXZaeiouyAEIOUY!@#%";
    $token = '';
    for ($i = 0; $i < 47; $i++) $token .= $char[(rand() % strlen($char))];

    // ***** Insert into Database *****
    $sql = "INSERT INTO api_tokens SET `token` = ?, customer_id = ?;";
    $this->db->query($sql, [$token, $customer_id];

    return array('http_code' => 200, 'token' => $token);
}