Cara menggunakan jwt::decode in php

saya lagi ngikut tutorial rest api codeigniter di playlist sekolah koding, nah di saat di bagian check token saya mendapat error saat ingin mendecode token Hasil dari Postman :
Cara menggunakan jwt::decode in php
Cara menggunakan jwt::decode in php
Routes :


Controller :

load->model('user');
	}

	public function response($data)
	{
		$this->output
			->set_content_type('application/json')
			->set_status_header(200)
			->set_output(json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
			->_display();

		exit;
	}

	public function register()
	{
		return $this->response($this->user->save());
	}

	public function get_all()
	{
		return $this->response($this->user->get());
	}

	public function get($id)
	{
		return $this->response($this->user->get('id', $id));
	}

	public function login()
	{

		$date = new DateTime();

		if (!$this->user->is_valid()) {
			return $this->response([
				'success' => false,
				'message' => 'email atau password salah'
			]);
		}

		$user = $this->user->get('email', $this->input->post('email'));
		// encode data
		$payload['id'] 		= $user->id;
		$payload['iat'] 	= $date->getTimestamp();
		$payload['exp'] 	= $date->getTimestamp() + 60 * 60 * 2;

		$output['id_token'] = JWT::encode($payload, $this->secret);
		$this->response($output);
	}

	public function check_token()
	{
		$jwt = $this->input->get_request_header('Authorization');

		try {
			$decoded = JWT::decode($jwt, $this->secret, array('HS256'));
			var_dump($decoded);
		} catch (\Exception $e) {
			// return $this->response([
			// 	'success' => false,
			// 	'message' => 'gagal, error token'
			// ]);
			var_dump($e);
		}
	}

	public function delete($id)
	{
		// check user login
		$this->check_token();
		// orang yang login yg mau hapus
	}
}
Models :
 $this->input->post('email'),
            'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
        ];

        if ($this->db->insert('users', $data)) {
            return [
                'id'      => $this->db->insert_id(),
                'success' => true,
                'message' => 'data berhasil dimasukan'
            ];
        }
    }

    public function get($key = null, $value = null)
    {
        if ($key != null) {
            $query = $this->db->get_where('users', array($key => $value));
            return $query->row();
        }

        $query = $this->db->get('users');
        return $query->result();
    }

    public function is_valid()
    {
        $email = $this->input->post('email');
        $password = $this->input->post('password');

        $hash = $this->get('email', $email)->password;

        if (password_verify($password, $hash))
            return true;

        return false;
    }
}

Hi! Today we will learn how to create an authentication on our CodeIgniter API. But before that let’s have a discussion about API and what is JSON Web Token(JWT).

API stands for Application Program Interface, API is an interface which allows applications exchange data. To make it more clear, API are set of functions that can be used by programmer to build software and applications.

JWT stands for JSON Web Token, it is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWT is commonly used for Authorization , Information Exchange and etc.

Now that we have a glimpse of idea on the topic, We will now proceed on building the app.

Step 1: Install CodeIgniter 4

For us to install CodeIgniter 4 we can install via composer or directly download CodeIgniter 4 here:

Install via composer:

composer create-project codeigniter4/appstarter ci-4-jwt

Step 2: Change CodeIgniter Environment

The default environment of CodeIgniter is production, it is a safety feature to add security in case settings are messed up when it goes live. For us to change the environment we will rename or copy the file env to .env. Once it is renamed, open the file and uncomment and change the CI_ENVIRONMENT value from production to development.

.env

CI_ENVIRONMENT = development

Step 3: Configure Database

After setting up the environment, we will then configure our database. You can configure it on .env or on the config file located at app/Config/Database.php. For this tutorial we will configure it on app/Config/Database.php.

Configure the database connection values:

app/Config/Database.php.

<?php
 
namespace Config;
 
use CodeIgniter\Database\Config;
 
/**
 * Database Configuration
 */
class Database extends Config
{
    /**
     * The directory that holds the Migrations
     * and Seeds directories.
     *
     * @var string
     */
    public $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
 
    /**
     * Lets you choose which connection group to
     * use if no other is specified.
     *
     * @var string
     */
    public $defaultGroup = 'default';
 
    /**
     * The default database connection.
     *
     * @var array
     */
    public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'ci_4_jwt',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'production'),
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];
 
    /**
     * This database connection is used when
     * running PHPUnit database tests.
     *
     * @var array
     */
    public $tests = [
        'DSN'      => '',
        'hostname' => '127.0.0.1',
        'username' => '',
        'password' => '',
        'database' => ':memory:',
        'DBDriver' => 'SQLite3',
        'DBPrefix' => 'db_',  // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'production'),
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];
 
    //--------------------------------------------------------------------
 
    public function __construct()
    {
        parent::__construct();
 
        // Ensure that we always set the database group to 'tests' if
        // we are currently running an automated test suite, so that
        // we don't overwrite live data on accident.
        if (ENVIRONMENT === 'testing')
        {
            $this->defaultGroup = 'tests';
        }
    }
 
    //--------------------------------------------------------------------
 
}

Step 4: Create A Model and Migration

Model – it a class that represents a database table.

Migration – like version control for the database that allows us to modify and share database schema to your team.

Execute this command on the Terminal or CMD to create a model:

php spark make:model UserModel

open the created model at app/Models/UserModel.php. Inside the file you can see configuration options, you can read the documentation to further learn about its configuration options. We will now update the configs:

app/Models/UserModel.php

<?php
 
namespace App\Models;
 
use CodeIgniter\Model;
 
class UserModel extends Model
{
    protected $DBGroup              = 'default';
    protected $table                = 'users';
    protected $primaryKey           = 'id';
    protected $useAutoIncrement     = true;
    protected $insertID             = 0;
    protected $returnType           = 'array';
    protected $useSoftDeletes       = false;
    protected $protectFields        = true;
    protected $allowedFields        = ['email', 'password'];
 
    // Dates
    protected $useTimestamps        = true;
    protected $dateFormat           = 'datetime';
    protected $createdField         = 'created_at';
    protected $updatedField         = 'updated_at';
    protected $deletedField         = 'deleted_at';
 
    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;
 
    // Callbacks
    protected $allowCallbacks       = true;
    protected $beforeInsert         = [];
    protected $afterInsert          = [];
    protected $beforeUpdate         = [];
    protected $afterUpdate          = [];
    protected $beforeFind           = [];
    protected $afterFind            = [];
    protected $beforeDelete         = [];
    protected $afterDelete          = [];
}

After creating the model, we will then create a migration file.

Execute this command on the Terminal or CMD to create a migration:

php spark make:migration AddUser

Open the created migration file on app/Database/Migrations/ and paste these codes:

<?php
 
namespace App\Database\Migrations;
 
use CodeIgniter\Database\Migration;
 
class AddUser extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
'type' => 'BIGINT',
'constraint' => 255,
'unsigned' => true,
'auto_increment' => true
            ],
            'email' => [
'type' => 'VARCHAR',
'unique' => true,
'constraint' => '255',
            ],
            'password' => [
'type' => 'VARCHAR',
'constraint' => '255',
            ],
            'created_at' => [
'type' => 'TIMESTAMP',
'null' => true
            ],
            'updated_at' => [
'type' => 'TIMESTAMP',
'null' => true
            ],
        ]);
        $this->forge->addPrimaryKey('id');
        $this->forge->createTable('users');
    }
 
    public function down()
    {
        $this->forge->dropTable('users');
    }
}

Run the migration by executing the 

CI_ENVIRONMENT = development
9 command:

php spark migrate

Step 5: Install JWT Package

We will then install the jwt package using composer:

composer require firebase/php-jwt

After installing the jwt package, add JWT_SECRET on the .env file

.env

#--------------------------------------------------------------------
# JWT
#--------------------------------------------------------------------
JWT_SECRET = 'JWT SECRET KEY SAMPLE HERE'

Step 6: Create Controllers

A Controller is the one responsible for receiving Request and returning Response.

Execute this command on the Terminal or CMD to create a the Controllers:

CI_ENVIRONMENT = development
0

After executing the command, it will create files located at app/Controllers. Open those file and insert these codes:

app/Controllers/Login.php

CI_ENVIRONMENT = development
1

app/Controllers/Register.php

CI_ENVIRONMENT = development
2

app/Controllers/User.php

CI_ENVIRONMENT = development
3

Step 7: Create Controller Filter

Controller Filters are classes that allows us to perform actions before or after the controllers execute.

We will now create Filter that will be used to check if a request is allowed and has authorization. Execute this command on the Terminal or CMD:

CI_ENVIRONMENT = development
4

After executing the command, it will create file located at app/Filters. Open this file and insert these codes:

app/Filters/AuthFilter.php

CI_ENVIRONMENT = development
5

After creating the filter, we must add it to filters config located at app/Config/Filters.php. We will creating an alias for our filter.

app/Config/Filters.php

CI_ENVIRONMENT = development
6

Step 8: Register Routes

Open the config file for routing located at app/Config/Routes.php and register these routes:

app/Config/Routes.php

CI_ENVIRONMENT = development
7

Step 9: Run the Application

Now that we have completed the steps above we will now run the app. To run the app, execute this command: