token based authentication in codeigniter rest server library
Asked Answered
P

2

13

I am try to build restful API in codeigniter using Phil Sturgeon's rest server

Problem is I can't figure out how to do token based authentication. I am building that API for mobile app and it is over HTTPS. At first user will authentication by logging in and then he will be able to use app functionalities. I want to implement in the way explained here: How token-based authentication works

Questions:

If I send token to server in request where should I check validity?
Does rest server library support token based authentication?
If it does which configurations do I need to do? or I need to implement my authentication methods?

or there is better/simpler way for authentication instead of token based?

Paestum answered 14/4, 2017 at 6:58 Comment(0)
J
9

It does not support token auth. Here's the modifications I made to add it. REST_Controller.php search for "switch ($rest_auth) {" add add this case to it:

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

Then add this function:

/** 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);
    }
}   

config/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';
Joseph answered 4/11, 2017 at 5:49 Comment(4)
how to use this? i do this all.how to get tokenWillette
I just added the controller and model function to get a token. There's a bit more work to be done on it and I actually changed the modifications to the rest library since the first answer.Joseph
And what about token expiry?Kaiserslautern
It's not built into the library. If I have time I may create an open source project to expand on the library to add into tokens and other stuff.Joseph
J
4

Controller to get the token:

I built a rest controllers to get the token.

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);
    }
}

Function in Model for Token:

/** 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);
}   
Joseph answered 9/1, 2018 at 18:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.