13

我正在尝试codeigniter使用 Phil Sturgeon 的休息服务器构建休息 API

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

问题:

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

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

4

2 回答 2

9

它不支持令牌认证。这是我为添加它所做的修改。REST_Controller.php 搜索 "switch ($rest_auth) {" 添加这个案例:

        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';
于 2017-11-04T05:49:49.117 回答
4

控制器获取令牌:

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

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);
}   
于 2018-01-09T18:52:32.497 回答