JWT(JSON Web Token) (Sixteen Token) Creation with CURL and Expire Time in CodeIgniter 3

 <?php

defined("BASEPATH") or exit("No direct script access allowed");

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class RequestSixteen extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
    }
    public function index()
    {
        $key = "Sixteen_Key";
        /*$data = [             //This is used in case of POST request to pass data
            "username" =>  "user@3944",
            "password" => "3228"
        ];*/

        //Set the expiration time to 2 hour from the current time
        $issuedAt = time();
        $expirationTime = $issuedAt + 7200;     //jwt valid for 2 hour from the issued time
        $payload = [
            "firstName" => "John",
            "lastName" => "doe",
            "executiveSummary" => "Below, you will find a proposal, etc. etc",
            "products" => [
                [
                    "name" => "test product",
                    "quantity" => 5,
                    "price" => 10,
                    "total" => 50
                ],
                [
                    "name" => "Creative Name",
                    "quantity" => 10,
                    "price" => 20,
                    "total" => 200
                ],
                [
                    "name" => "Other",
                    "quantity" => 100,
                    "price" => 200,
                    "total" => 2000
                ]
            ],
            "additional" => [
                [
                    "name" => "Arbitrary Name",
                    "value" => "Additional Value"
                ],
                [
                    "name" => "Other Arbitrary Name",
                    "value" => "Really Long value Here, Anything goes."
                ],
            ],
            "terms" => [
                [
                    "text" => "Lorem Ipsum dolor sit amet, consectetur adipiscing elit.
                            Donec eu finibus massa. Ut et purus odio. Donec pellentesque,
                            urna quis molestie bibendum, nibh tortor dapibus leo, sit amet
                            tincidunt mauris mi eu quam."
                ],
                [
                    "text" => "Etiam id felis a velit egestas aliquam at vel est. In quis tristique lacus.
                            Vestibulum sit amet nisi nisi. Proin a mauris pellentesque, condimentum
                            ex ut, euismod orci."
                ],
                [
                    "text" => "Quisque laoreet tincidunt velit, sit amet placerat mi suscipit ac. Ut laoreet
                            et nibh id mattis. Cras sed felis malesueda, facilisis libero in, dapidus felis.
                            Nunc sit amet egastas velit. Integer id mollis nisi."
                ],
            ],
            "iat" => $issuedAt,         //Issued at: time when the token was generated
            "nbf" => $issuedAt,         //Not before
            "exp" => $expirationTime    //Expiration time
        ];

        $jwt = JWT::encode($payload, $key, "HS256");

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => 'http://localhost/blogApi/ApiSixteen/users',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            //CURLOPT_POSTFIELDS => json_encode($data), //It is used in case of POST Request
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
                'Authorization: Bearer ' . $jwt,
            ],
        ]);

        $response = curl_exec($curl);
        curl_close($curl);
        print_r($response);
    }
}






DECODE Data File
<?php
defined("BASEPATH") or exit("No direct script access allowed");

use chriskacerguis\RestServer\RestController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class ApiSixteen extends RestController
{
    public function __construct()
    {
        parent::__construct();
    }
    public function users_get()
    {
        $headers = apache_request_headers();

        $jwt = $headers["Authorization"];

        $jwt = str_replace("Bearer", "", $jwt);
        $jwt = trim($jwt);
        print_r($jwt);
        echo "<br><br><br>";

        try {
            $decoded = JWT::decode($jwt, new Key("Sixteen_Key", "HS256"));
            echo json_encode(array(
                "status" => "success",
                "data" => $decoded
            ));
            echo "<br><br><br>";
            echo "<pre>";
            $this->response($decoded);
        } catch (\Firebase\JWT\ExpiredException $e) {
            echo json_encode(array(
                "status" => "error",
                "message" => "Token is Expired"
            ));
        } catch (Exception $e) {
            echo json_encode(array(
                "status" => "error",
                "message" => $e->getMessage()
            ));
            print_r($e->getMessage());
            exit();
        }
    }
}

Comments