Thursday, 8 November 2018

Jwt in php codeigniter framework

Jwt in php Codeigniter framework, My internet connection is  Airtel

Follow the steps as shown in given video

 



In controller Test.php


<?php
require APPPATH . '/libraries/ImplementJwt.php';

class Test extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->objOfJwt = new ImplementJwt();
        header('Content-Type: application/json');
    }

    /////////// Generating Token and put user data into  token ///////////

    public function LoginToken()
    {
            $tokenData['uniqueId'] = '55555';
            $tokenData['role'] = 'admin';
            $tokenData['timeStamp'] = Date('Y-m-d h:i:s');
            $jwtToken = $this->objOfJwt->GenerateToken($tokenData);
            echo json_encode(array('Token'=>$jwtToken));
         }
    
    //////// get data from token ////////////
        
    public function GetTokenData()
    {
    $received_Token = $this->input->request_headers('Authorization');
        try
            {
            $jwtData = $this->objOfJwt->DecodeToken($received_Token['Token']);
            echo json_encode($jwtData);
            }
            catch (Exception $e)
            {
            http_response_code('401');
            echo json_encode(array( "status" => false, "message" => $e->getMessage()));exit;
            }
    }
}

 

Step 2: ImplementJwt.php

 <?php
require APPPATH . '/libraries/JWT.php';


class ImplementJwt
{
  

    //////////The function generate token/////////////
    PRIVATE $key = "subcribe_my_channel"; // url: https://www.youtube.com/watch?v=zD4IGp1lBWs
    public function GenerateToken($data)
    {         
        $jwt = JWT::encode($data, $this->key);
        return $jwt;
    }
   


   //////This function decode the token////////////////////
    public function DecodeToken($token)
    {         
        $decoded = JWT::decode($token, $this->key, array('HS256'));
        $decodedData = (array) $decoded;
        return $decodedData;
    }
}
?> 

Download  jwt library: 


https://github.com/firebase/php-jwt

To check jwt token data:


https://jwt.io/

 

 

6 comments: