Search code examples
phprestcodeignitercodeigniter-3

How to make token authentication in Codeigniter 3 REST API


So i just finished making REST API in Codeigniter 3 and i wanted to make an authentication with token, so i used the JWT from this repo https://github.com/ParitoshVaidya/CodeIgniter-JWT-Sample/tree/CI3 My question is, how do i make my API Controller to require the token for every request ? This is my api controller

function __construct($config = 'rest') {
        parent::__construct($config);   
        $this->load->helper(array('text','url'));
        $this->load->model('Api_model');        
    }
    
    // GET ARTICLE
    function index_get(){
        $data = $this->Api_model->get_all_article();
        return $this->response($data,200);
    }

and this is my token controller

public function token_get()
    {
        $tokenData = array();
        $tokenData['id'] = 1;        
        $output['token'] = AUTHORIZATION::generateToken($tokenData);
        $this->set_response($output, REST_Controller::HTTP_OK);
    }

Solution

  • I recommend moving the token-logic into a library. Then you'll have it available in all controllers and do not have to do a dirty instanciating of a controller inside your api controller.

    Add class application\libraries\Token.php

    <?php
    defined('BASEPATH') OR exit('No direct script access allowed');
    class Token {
    
            public function token_get()
            {
                    $tokenData = array();
                    $tokenData['id'] = 1;        
                    $output['token'] = AUTHORIZATION::generateToken($tokenData);
                    $this->set_response($output, REST_Controller::HTTP_OK); // <--
            }
    }
    

    You will have to make this REST_Controller available in your library or change this logic accordingly.

    Then in your APIController:

    function token_get(){
        $this->load->library('Token');
        return $this->Token->token_get();
    }
    
    // GET ARTICLE
    function index_get(){
        $token = $this->token_get(); // added this line
        $data = $this->Api_model->get_all_article();
        return $this->response($data,200);
    }
    

    Read more about Libraries in CodeIgniter