CodeIgniter 4: Build a JWT Token-Based Authentication System
A complete guide to implementing stateless JSON Web Token authentication in CodeIgniter 4 to protect RESTful APIs.
For modern RESTful APIs and decoupled applications such as React or Vue SPAs and mobile apps, traditional session-based authentication is not always the best choice. JSON Web Tokens (JWT) are a standard solution for stateless, secure and scalable authentication.
Why use JWT with CodeIgniter 4
Integrating JWT into CodeIgniter 4 provides several architectural advantages:
- Stateless: the server does not need to store session state in a database or cache for every request.
- Native filters: CodeIgniter 4 Filters can intercept and validate the authorization header before controllers run.
- Flexibility: the token carries the payload needed to identify the user and their roles in a signed form.
1. Configure the secret key and dependencies
First, install the standard JWT library through Composer:
composer require firebase/php-jwt
Next, define a strong secret key in the project's .env file to sign tokens:
JWT_SECRET_KEY = 'la_tua_chiave_segreta_molto_lunga_e_sicura'
JWT_TIME_TO_LIVE = 3600
2. Generate the token at login
In the authentication controller, for example AuthController.php, validate the user's credentials and generate a JWT returned as JSON when they are correct:
request->getVar('email');
$password = $this->request->getVar('password');
$userModel = new \App\Models\UserModel();
$user = $userModel->where('email', $email)->first();
if (!$user || !password_verify($password, $user['password'])) {
return $this->failUnauthorized('Credenziali non valide');
}
$key = getenv('JWT_SECRET_KEY');
$iat = time();
$exp = $iat + (int)getenv('JWT_TIME_TO_LIVE');
$payload = [
'iss' => 'athesis_api',
'sub' => $user['id'],
'iat' => $iat,
'exp' => $exp,
'email'=> $user['email']
];
$token = JWT::encode($payload, $key, 'HS256');
return $this->respond([
'status' => 200,
'message' => 'Login effettuato con successo',
'token' => $token,
'expires' => $exp
]);
}
}
3. Protect routes with a JWT filter
To validate the token for every protected request, create a filter in App/Filters/JWTAuthFilter.php:
getHeaderLine('Authorization');
$token = null;
if (!empty($header) && preg_match('/Bearer\s(\S+)/', $header, $matches)) {
$token = $matches[1];
}
if (!$token) {
return service('response')
->setStatusCode(401)
->setJSON(['message' => 'Token di accesso mancante o non valido']);
}
try {
$key = getenv('JWT_SECRET_KEY');
$decoded = JWT::decode($token, new Key($key, 'HS256'));
} catch (Exception $e) {
return service('response')
->setStatusCode(401)
->setJSON(['message' => 'Token scaduto o non autorizzato: ' . $e->getMessage()]);
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
}
}
Conclusion
JWT in CodeIgniter 4 supports a clean, lightweight API architecture ready for integration with any modern frontend. Native Filters combined with Firebase PHP-JWT make protected routes straightforward to manage and maintain.
Official sources
Share
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0