Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
token based authentication in codeigniter rest server library

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?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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';
about 4 years ago · Santiago Trujillo Relatório

0

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);
}   
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda