CodeIgniter 4 RESTful APIs with JWT Authentication

Share this Article
Reading Time: 12 minutes
21,720 Views

Inside this article we will start about the development of CodeIgniter 4 RESTful APIs with JWT authentication. API Development in CodeIgniter 4, a little bit different approach from old CodeIgniter versions.

JSON Web Tokens (JWT) is a way of stateless handling user authentication. What does it mean? Well, JWT helps to organize authentication without storing the authentication state in any storage be it a session or a database.

We will create user authentication APIs using JWT –

  • Login API
  • Register API
  • Details API
  • Understand Logout Function

Step by step we will create CodeIgniter 4 APIs with JWT. It will be very interesting topic to learn and implement. We will use JWT (Json Web Token) for authentication here for RESTful web services. CodeIgniter developers surely love this article.

Learn More –

  • CodeIgniter 4 CRUD REST APIs Development, Click here.
  • REST API Development with Validation in CodeIgniter 4, Click here.
  • Basic Auth REST API Development in CodeIgniter 4, Click here.
  • Upload Image by REST API in CodeIgniter 4 Tutorial, Click here.

Let’s get started.


CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.


.env Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file.

Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.


Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE codeigniter4_app;

Successfully, we have created a database.


Create Database Table

Next, we need to create a table inside database.

CREATE TABLE `users` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) DEFAULT NULL,
 `email` varchar(120) DEFAULT NULL,
 `phone_no` varchar(30) DEFAULT NULL,
 `password` varchar(120) DEFAULT NULL,
 `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Database Connection

Open .env file from project root.

Search for DATABASE. You should see the connection environment variables. Give your updated details of database connection string.

 
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = codeigniter4_app
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
database.default.DBPrefix =
   

Now, database successfully connected with the application.


Install JWT Composer Package

Open project into terminal and run this composer command to install JWT package.

$ composer require firebase/php-jwt

It will install jwt package into /vendor folder at project root.


Create Routes

Open Routes.php from /app/Config folder. Add these routes into it.

//...

$routes->group("api", function ($routes) {

    $routes->post("register", "User::register");
    $routes->post("login", "User::login");
    $routes->get("profile", "User::details");
});

//...

Next, we need a model file.


Create Model

Back to terminal and run this spark command to create a model file.

$ php spark make:model User --suffix

This command will creates UserModel.php file at /app/Models folder.

Open UserModel.php and write this complete code into it.

<?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 $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
		"name", 
		"email", 
		"phone_no",
		"password"
	];

	// Dates
	protected $useTimestamps        = false;
	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          = [];
}

Create Controller

Again, Back to terminal and run this spark command to create a controller file.

$ php spark make:controller User

It will creates User.php file at /app/Controllers folder.

Open User.php and write this complete code into it.

<?php

namespace App\Controllers;

use App\Models\UserModel;
use CodeIgniter\RESTful\ResourceController;
use Exception;
use \Firebase\JWT\JWT;

class User extends ResourceController
{
    public function register()
    {
        $rules = [
            "name" => "required",
            "email" => "required|valid_email|is_unique[users.email]|min_length[6]",
            "phone_no" => "required",
            "password" => "required",
        ];

        $messages = [
            "name" => [
                "required" => "Name is required"
            ],
            "email" => [
                "required" => "Email required",
                "valid_email" => "Email address is not in format"
            ],
            "phone_no" => [
                "required" => "Phone Number is required"
            ],
            "password" => [
                "required" => "password is required"
            ],
        ];

        if (!$this->validate($rules, $messages)) {

            $response = [
                'status' => 500,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => []
            ];
        } else {

            $userModel = new UserModel();

            $data = [
                "name" => $this->request->getVar("name"),
                "email" => $this->request->getVar("email"),
                "phone_no" => $this->request->getVar("phone_no"),
                "password" => password_hash($this->request->getVar("password"), PASSWORD_DEFAULT),
            ];

            if ($userModel->insert($data)) {

                $response = [
                    'status' => 200,
                    "error" => false,
                    'messages' => 'Successfully, user has been registered',
                    'data' => []
                ];
            } else {

                $response = [
                    'status' => 500,
                    "error" => true,
                    'messages' => 'Failed to create user',
                    'data' => []
                ];
            }
        }

        return $this->respondCreated($response);
    }

    private function getKey()
    {
        return "my_application_secret";
    }

    public function login()
    {
        $rules = [
            "email" => "required|valid_email|min_length[6]",
            "password" => "required",
        ];

        $messages = [
            "email" => [
                "required" => "Email required",
                "valid_email" => "Email address is not in format"
            ],
            "password" => [
                "required" => "password is required"
            ],
        ];

        if (!$this->validate($rules, $messages)) {

            $response = [
                'status' => 500,
                'error' => true,
                'message' => $this->validator->getErrors(),
                'data' => []
            ];

            return $this->respondCreated($response);
            
        } else {
            $userModel = new UserModel();

            $userdata = $userModel->where("email", $this->request->getVar("email"))->first();

            if (!empty($userdata)) {

                if (password_verify($this->request->getVar("password"), $userdata['password'])) {

                    $key = $this->getKey();

                    $iat = time(); // current timestamp value
                    $nbf = $iat + 10;
                    $exp = $iat + 3600;

                    $payload = array(
                        "iss" => "The_claim",
                        "aud" => "The_Aud",
                        "iat" => $iat, // issued at
                        "nbf" => $nbf, //not before in seconds
                        "exp" => $exp, // expire time in seconds
                        "data" => $userdata,
                    );

                    $token = JWT::encode($payload, $key);

                    $response = [
                        'status' => 200,
                        'error' => false,
                        'messages' => 'User logged In successfully',
                        'data' => [
                            'token' => $token
                        ]
                    ];
                    return $this->respondCreated($response);
                } else {

                    $response = [
                        'status' => 500,
                        'error' => true,
                        'messages' => 'Incorrect details',
                        'data' => []
                    ];
                    return $this->respondCreated($response);
                }
            } else {
                $response = [
                    'status' => 500,
                    'error' => true,
                    'messages' => 'User not found',
                    'data' => []
                ];
                return $this->respondCreated($response);
            }
        }
    }

    public function details()
    {
        $key = $this->getKey();
        $authHeader = $this->request->getHeader("Authorization");
        $authHeader = $authHeader->getValue();
        $token = $authHeader;

        try {
            $decoded = JWT::decode($token, $key, array("HS256"));

            if ($decoded) {

                $response = [
                    'status' => 200,
                    'error' => false,
                    'messages' => 'User details',
                    'data' => [
                        'profile' => $decoded
                    ]
                ];
                return $this->respondCreated($response);
            }
        } catch (Exception $ex) {
          
            $response = [
                'status' => 401,
                'error' => true,
                'messages' => 'Access denied',
                'data' => []
            ];
            return $this->respondCreated($response);
        }
    }
}

We have all methods available like for login, register and all.


How to Log Out when using JWT

JWT helps to manage authentication without storing the authentication state in any storage be it a session or a database.

So, basically whenever a token is created, it can be used forever, or until it is expired. JWT generator can get an option to invalidate the token after a specified time.

When using JWT authentication, the client side stores the token somewhere and attaches it to every request that needs authentication. This is how the request processes with JWT.

Now, to expire a token and or make it invalid we need to set expiration time while creating tokens.

 $iat = time();
 $nbf = $iat + 10;
 $exp = $iat + 3600;

 $payload = array(
     "iss" => "The_claim",
     "aud" => "The_Aud",
     "iat" => $iat,
     "nbf" => $nbf,
     "exp" => $exp,
     "data" => $userdata,
 );

 $token = JWT::encode($payload, $key);

As, in the above code we can see we are creating JWT in which we are setting expiration time. So you need to set your own time for that. After that period token will not be used. It will become invalid.


Application Testing

Start development server:

$ php spark serve

REGISTER API

URL: http://localhost:8080/api/register

METHOD: POST

HEADERS:

Content-Type:application/json
Accept:application/json

HANDLER: \App\Controllers\User::register

API Data Validation

API Call with Data

LOGIN API

URL: http://localhost:8080/api/login

METHOD: POST

HEADERS:

Content-Type:application/json
Accept:application/json

HANDLER: \App\Controllers\User::login

PROFILE API

URL: http://localhost:8080/api/profile

METHOD: GET

HEADERS:

Content-Type:application/json
Accept:application/json
Authorization:<TOKEN>

HANDLER: \App\Controllers\User::details

To learn about CodeIgniter 4 RESTful Resource controller, click here.

We hope this article helped you to learn about CodeIgniter 4 RESTful APIs with JWT Authentication in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

12 thoughts on “CodeIgniter 4 RESTful APIs with JWT Authentication”

  1. Why is the getkey function public? It will be seen in browser. It should be secret.

      • I’m making a RBAC system in codeigniter 4.1.1 using adminlte3 as frontend template.
        i mean, should I develop the system non-rest as in another tutorial in which you teach us how to make a role-based system and apply the restful jwt later in CRUD operations?
        i’m sorry for my dumb questions
        🙂 thx

Comments are closed.

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5