Mastering API Login in CodeIgniter 4: A Comprehensive Guide

Yash Kumar Prasad
4 min readOct 10, 2024

--

Introduction:

With present day packages more and more relying on APIs for verbal exchange among client and server, stable authentication has end up a critical issue of building internet applications. CodeIgniter four, a light-weight and flexible PHP framework, presents developers with the equipment to quickly construct and steady APIs.

In this educational, we will manual you thru the procedure of implementing API login capability the use of CodeIgniter 4. We will cover putting in CodeIgniter, developing an API for person authentication, and securing your endpoints using token-primarily based authentication.

Setting Up CodeIgniter 4 for API Development

Before we dive into building the API, you need to set up CodeIgniter 4. If you haven’t installed CodeIgniter yet, follow these steps:

  1. Install CodeIgniter 4 via Composer:
composer create-project codeigniter4/appstarter api-login-example
cd api-login-example

2. Set Up Environment Variables: Update your .env file with the database configuration. Create a new MySQL database, then update the following fields:

database.default.hostname = localhost
database.default.database = api_login_db
database.default.username = root
database.default.password = password
database.default.DBDriver = MySQLi

3. Set Up Basic Project Structure: Inside your app/ folder, you will place controllers, models, and other files needed for your API.

Implementing API Authentication

What Is Token-Based Authentication?

Token-primarily based authentication is extensively used for securing APIs. It includes imparting the patron with a token after a success login, which the consumer should ship with every subsequent request. In this manual, we will use JSON Web Tokens (JWT) for coping with authentication.

Installing JWT Library

To implement JWT in CodeIgniter, you need to install the firebase/php-jwt library. Run this command:

composer require firebase/php-jwt

Creating the User Model

First, you’ll need a User model to interact with the users' database table.

Create a new file in app/Models/UserModel.php:

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['username', 'email', 'password'];
protected $returnType = 'array';
}

Creating User Table Migration

Now create a migration to generate the users table:

php spark make:migration CreateUsersTable

In app/Database/Migrations/XXXXXX_CreateUsersTable.php, define the fields:

public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'unsigned' => true,
'auto_increment' => true
],
'username' => [
'type' => 'VARCHAR',
'constraint' => '100',
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '100',
],
'password' => [
'type' => 'VARCHAR',
'constraint' => '255',
],
]);
$this->forge->addKey('id', true);
$this->forge->createTable('users');
}

Run the migration:

php spark migrate

Creating a Secure Login Endpoint

Creating the Auth Controller

Now we need to create an AuthController to handle user login and token generation. Create a new controller in app/Controllers/AuthController.php:

<?php

namespace App\Controllers;

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

class AuthController extends ResourceController
{
protected $userModel;

public function __construct()
{
$this->userModel = new UserModel();
}

public function login()
{
$email = $this->request->getVar('email');
$password = $this->request->getVar('password');

// Validate input
if (!$email || !$password) {
return $this->fail('Email and Password required', 400);
}

// Find user by email
$user = $this->userModel->where('email', $email)->first();

if (!$user || !password_verify($password, $user['password'])) {
return $this->fail('Invalid credentials', 401);
}

// Generate JWT token
$key = getenv('JWT_SECRET');
$payload = [
"iss" => "api-login", // Issuer
"aud" => "users", // Audience
"iat" => time(), // Issued at
"exp" => time() + 3600, // Expiration time (1 hour)
"data" => [
"id" => $user['id'],
"email" => $user['email']
]
];

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

return $this->respond([
'status' => 200,
'message' => 'Login successful',
'token' => $token
]);
}
}

Defining the JWT Secret

In your .env file, add the JWT secret:

JWT_SECRET=your_jwt_secret_key

Securing API Endpoints

To protect your API endpoints, you can create a filter that verifies the JWT token. Create a new filter JWTAuth.php in app/Filters:

<?php

namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Firebase\JWT\JWT;
use Exception;

class JWTAuth implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
$authHeader = $request->getServer('HTTP_AUTHORIZATION');

if (!$authHeader) {
return Services::response()->setJSON(['message' => 'Unauthorized'])->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
}

$token = explode(' ', $authHeader)[1];

try {
$decoded = JWT::decode($token, new Key(getenv('JWT_SECRET'), 'HS256'));
} catch (Exception $e) {
return Services::response()->setJSON(['message' => 'Invalid token'])->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
}
}

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

Enable this filter in app/Config/Filters.php:

public $aliases = [
'jwt' => \App\Filters\JWTAuth::class,
];

public $globals = [
'before' => [],
'after' => [],
];

public $methods = [
'post' => ['jwt'],
];

Testing and Debugging

You can use Postman to test your login API:

  1. Login:
  • Set up a POST request to /auth/login.
  • Provide the email and password in the body.
  • You should receive a token in the response

2. Secure Endpoints:

  • For secure endpoints, include the token in the Authorization header as Bearer <token>.

Conclusion

In this guide, we covered how to enforce API login the use of CodeIgniter four with JWT-based totally authentication. We began with putting in CodeIgniter, moved to growing a steady login endpoint, after which secured our API endpoints using JWT tokens.

You now have a foundational setup to build extra superior capabilities, along with function-based totally get entry to manage, refresh tokens, and extra, into your API.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Yash Kumar Prasad
Yash Kumar Prasad

Written by Yash Kumar Prasad

Full-stack developer with a passion for crafting robust web solutions. Experienced in creating scalable applications that prioritize user experience.

No responses yet

Write a response