Building a Secure RESTful API with CodeIgniter 4 and JWT Authentication

A hands-on guide to securing CodeIgniter 4 REST APIs with JWT tokens: configuration, login, an authentication filter, and ready-to-use code examples.

Building a Secure RESTful API with CodeIgniter 4 and JWT Authentication

Exposing data through a REST API is standard practice for any modern web application, but an open API with no access control is an invitation to serious trouble: data theft, abuse of server resources, privacy breaches. In this tutorial we build a secure RESTful API from scratch with CodeIgniter 4, protecting the endpoints with JSON Web Token (JWT) authentication, one of the most widely used standards for authenticating stateless clients (mobile apps, JavaScript frontends, external services) without having to keep server-side sessions.

This tutorial assumes you already have a basic knowledge of PHP and CodeIgniter 4, but have not yet implemented a token-based authentication system: we will explain every step, from setting up the project to verifying the token on every request.

What a JWT is, and why use it for a REST API

A JSON Web Token is a compact, self-contained string made of three parts separated by a dot: header, payload and signature. The payload holds information about the user (for example their ID) and an expiration date, while the signature guarantees that no one can tamper with the token's content without being detected, since it is generated with a secret key known only to the server.

Unlike traditional PHP sessions, which require the server to keep state (session data saved to disk or to a database), a JWT is stateless: the client sends it with every request in the Authorization header, and the server verifies it mathematically, without having to query any storage. This makes it ideal for APIs consumed by mobile apps, single-page applications, or other backend services.

Prerequisites

  • PHP 8.2 or higher: this is the minimum requirement of the current CodeIgniter 4 releases (the 4.7.x series), with the intl and mbstring extensions enabled.
  • Composer, to install the project's dependencies.
  • An already-started CodeIgniter 4 project (composer create-project codeigniter4/appstarter project-name), or an existing project you want to secure.
  • A MySQL/MariaDB (or compatible) database already configured in app/Config/Database.php, with a users table.

Installing the JWT library via Composer

CodeIgniter 4 doesn't include built-in JWT support, but it integrates smoothly with firebase/php-jwt, the most widely used library in the PHP ecosystem for creating and verifying tokens (at the time of writing it is at version 7.2.1, compatible with PHP 8.0 and above). From the project root:

composer require firebase/php-jwt

Composer will download the library into vendor/firebase/php-jwt and make it available through the autoloading CodeIgniter already sets up.

Setting the secret key in the .env file

The secret key used to sign and verify tokens must never be hard-coded directly in your source, but stored in the .env file (excluded from version control). Open (or create, copying it from env) the .env file in the project root and add:

#--------------------------------------------------------------------
# JWT
#--------------------------------------------------------------------

JWT_SECRET_KEY = 'a-long-random-string-generated-specifically-for-this'
JWT_EXPIRE_SECONDS = 3600

Generate a strong key, for example with openssl rand -base64 48 from the command line, and never reuse the same key between your development and production environments.

To read these values conveniently, create a small configuration file, app/Config/JwtConfig.php:

secretKey = env('JWT_SECRET_KEY', '');
        $this->expireSeconds = (int) env('JWT_EXPIRE_SECONDS', 3600);
    }
}

Creating the login endpoint that issues the token

Suppose you already have a UserModel representing the users table, with a password_hash column generated with password_hash() (never store passwords in plain text or with weak hashing algorithms). Let's create a dedicated authentication controller, app/Controllers/Api/AuthController.php:

request->getPost('email');
        $password = $this->request->getPost('password');

        if (! $email || ! $password) {
            return $this->response->setStatusCode(400)->setJSON([
                'status'  => 400,
                'message' => 'Email and password are required.',
            ]);
        }

        $userModel = new UserModel();
        $user      = $userModel->where('email', $email)->first();

        if (! $user || ! password_verify($password, $user->password_hash)) {
            return $this->response->setStatusCode(401)->setJSON([
                'status'  => 401,
                'message' => 'Invalid credentials.',
            ]);
        }

        $jwtConfig = config(JwtConfig::class);
        $issuedAt  = time();

        $payload = [
            'iss'  => base_url(),
            'sub'  => $user->id,
            'iat'  => $issuedAt,
            'exp'  => $issuedAt + $jwtConfig->expireSeconds,
        ];

        $token = JWT::encode($payload, $jwtConfig->secretKey, $jwtConfig->algorithm);

        return $this->response->setJSON([
            'status'     => 200,
            'token'      => $token,
            'expires_in' => $jwtConfig->expireSeconds,
        ]);
    }
}

The payload includes the three most common standard claims: iss (issuer, who issued the token), sub (subject, the authenticated user's ID) and exp (expiration, the moment the token stops being valid). Avoid putting sensitive data such as the password in the payload: a JWT is signed but not encrypted, so anyone who intercepts the token can read its content simply by decoding it from base64.

Creating a Filter to protect the endpoints

In CodeIgniter 4 the correct way to intercept every request to protected routes, before it even reaches the controller, is a Filter. Let's create app/Filters/JwtAuthFilter.php:

getHeaderLine('Authorization');

        if (! $authHeader || ! preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
            return service('response')->setStatusCode(401)->setJSON([
                'status'  => 401,
                'message' => 'Missing authentication token.',
            ]);
        }

        $token     = $matches[1];
        $jwtConfig = config(JwtConfig::class);

        try {
            $decoded = JWT::decode($token, new Key($jwtConfig->secretKey, $jwtConfig->algorithm));

            // Makes the user ID available to controllers through the request object.
            $request->userId = $decoded->sub;
        } catch (ExpiredException $e) {
            return service('response')->setStatusCode(401)->setJSON([
                'status'  => 401,
                'message' => 'Token expired.',
            ]);
        } catch (SignatureInvalidException $e) {
            return service('response')->setStatusCode(401)->setJSON([
                'status'  => 401,
                'message' => 'Invalid token.',
            ]);
        } catch (\Exception $e) {
            return service('response')->setStatusCode(401)->setJSON([
                'status'  => 401,
                'message' => 'Authentication failed.',
            ]);
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // No action needed after the response.
    }
}

The filter reads the Authorization header, checks that it follows the Bearer format, then uses JWT::decode() to validate the signature and expiration. If anything is off, it stops the request right there and returns a JSON response with a 401 status code, without the controller ever running.

Registering the filter in the configuration

Open app/Config/Filters.php and register the filter with an alias, then assign it to the API routes:

public array $aliases = [
    // ... existing aliases ...
    'jwtAuth' => \App\Filters\JwtAuthFilter::class,
];

The cleanest way to apply the filter only to protected endpoints is directly in the routes, in app/Config/Routes.php:

$routes->post('api/auth/login', 'Api\AuthController::login');

$routes->group('api', ['filter' => 'jwtAuth'], function ($routes) {
    $routes->resource('articles', ['controller' => 'Api\ArticlesController']);
    $routes->get('api/me', 'Api\AuthController::me');
});

This way the login endpoint stays public (it is, after all, how clients obtain the token), while every route inside the group requires a valid JWT to be reached.

A sample protected endpoint

A typical REST controller in CodeIgniter 4 extends ResourceController, which already provides the standard methods (index, show, create, update, delete) mapped to the correct HTTP verbs. Here is an excerpt of app/Controllers/Api/ArticlesController.php using the user ID the filter set:

where('user_id', $this->request->userId)
            ->findAll();

        return $this->respond($articles, 200);
    }
}

Thanks to the filter, by the time this code runs we can be sure the request comes from an authenticated user, and that $this->request->userId holds their real ID, without having to re-check it in the controller.

Testing the API with curl

First, let's obtain a token with a login request:

curl -X POST https://your-site.test/api/auth/login \
  -d "email=user@example.com" \
  -d "password=secret-password"

The response will include a token field. Let's use it to call a protected endpoint:

curl https://your-site.test/api/articles \
  -H "Authorization: Bearer "

If the token is missing, expired, or tampered with, the API will respond with a 401 status code before even running the controller logic: exactly the behavior we expect from a filter that correctly protects the routes.

Additional best practices

  • Short token lifetimes: set tight expirations (for example 15-60 minutes) and, if a longer session is needed, implement a separate refresh token system, stored securely and revocable server-side.
  • HTTPS required: a JWT sent in the clear over HTTP can be intercepted and reused by anyone; in production the entire API must be served only over HTTPS.
  • Rate limiting on login: the login endpoint is a typical target for brute-force attacks; consider throttling requests (CodeIgniter 4 ships with a built-in Throttler service).
  • Strict algorithm validation: always explicitly specify the algorithm (HS256) both when encoding and decoding, to avoid attacks that try to get tokens signed with weak or "none" algorithms accepted.
  • Never rely on the payload alone for complex authorization: the JWT tells you who the user is, but for more granular permissions and roles it is often better to check the current state in the database, because an already-issued token does not automatically "update" if the user's permissions change before it expires.

Conclusion

With just a few files — a configuration class, an authentication controller and a filter — CodeIgniter 4 lets you build a solid, fully stateless JWT authentication system, suited to both JavaScript frontends and mobile apps. The firebase/php-jwt library handles the cryptographic side, while the framework's Filters system makes applying access control declarative and easy to maintain as the number of endpoints grows.

Official sources

Share

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Angry Angry 0
Sad Sad 0
Wow Wow 0