Skip to content

Codeigniter 9: Building a Secure REST API in CodeIgniter with JWT Authentication

Computer pc and laptop with programming code on screens at software development company.

Codeigniter 9: Building a Secure REST API in CodeIgniter with JWT Authentication

Security is a critical aspect of REST API development. JSON Web Tokens (JWT) provide a robust method for implementing stateless authentication in your API. In this guide, we’ll walk through setting up JWT authentication in CodeIgniter to secure your REST API.

 

What is JWT?
 

JWT (JSON Web Token) is an open standard (RFC 7519) for securely transmitting information between a client and a server. It is compact, self-contained, and allows for stateless authentication.

  • Structure: A JWT consists of three parts:
    1. Header: Contains the token type and signing algorithm.
    2. Payload: Includes claims (e.g., user information).
    3. Signature: Ensures the token’s integrity.

 

Step 1: Install JWT Library
 

To use JWT in your CodeIgniter project, install the Firebase JWT library via Composer:

composer require firebase/php-jwt

 

Step 2: Generate a JWT Token
 

Create a method to generate JWT tokens upon successful user authentication.

  1. Update the Controller: Add the use statement for the JWT library and define a method to generate tokens:
    namespace App\Controllers;
    
    use Firebase\JWT\JWT;
    use Firebase\JWT\Key;
    use CodeIgniter\RESTful\ResourceController;
    
    class AuthController extends ResourceController {
        private $secretKey = "your_secret_key";
    
        public function login() {
            $credentials = $this->request->getJSON();
    
            // Example: Validate user credentials
            if ($credentials->email === "admin@example.com" && $credentials->password === "password") {
                $payload = [
                    "iss" => "http://localhost", // Issuer
                    "aud" => "http://localhost", // Audience
                    "iat" => time(), // Issued at
                    "exp" => time() + 3600, // Expiration
                    "data" => [
                        "email" => $credentials->email
                    ]
                ];
    
                $token = JWT::encode($payload, $this->secretKey, 'HS256');
                return $this->respond(['token' => $token]);
            }
    
            return $this->failUnauthorized('Invalid credentials');
        }
    }
  2. Test Token Generation:
    • Use Postman or cURL to send a POST request to your login endpoint with the user credentials.
    • The response should include a JWT token.

 

Step 3: Validate JWT Tokens
 

Create middleware or filters to validate the token on protected endpoints.

  1. Create a JWT Filter:
    namespace App\Filters;
    
    use CodeIgniter\HTTP\RequestInterface;
    use CodeIgniter\HTTP\ResponseInterface;
    use CodeIgniter\Filters\FilterInterface;
    use Firebase\JWT\JWT;
    use Firebase\JWT\Key;
    
    class JWTFilter implements FilterInterface {
        private $secretKey = "your_secret_key";
    
        public function before(RequestInterface $request, $arguments = null) {
            $authHeader = $request->getHeaderLine('Authorization');
    
            if (!$authHeader) {
                return Services::response()->setJSON(['error' => 'Authorization header missing'])->setStatusCode(401);
            }
    
            $token = str_replace('Bearer ', '', $authHeader);
    
            try {
                $decoded = JWT::decode($token, new Key($this->secretKey, 'HS256'));
            } catch (\Exception $e) {
                return Services::response()->setJSON(['error' => 'Invalid token'])->setStatusCode(401);
            }
        }
    
        public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {
            // No action needed after the request
        }
    }
  2. Register the Filter: Add the filter in app/Config/Filters.php:
    public $aliases = [
        'jwtAuth' => \App\Filters\JWTFilter::class,
    ];
  3. Protect Routes: Apply the filter to secure routes in app/Config/Routes.php:
    $routes->group('api', ['filter' => 'jwtAuth'], function ($routes) {
        $routes->get('users', 'UserController::index');
    });

 

Step 4: Testing Secure Endpoints
 

  1. Login to Obtain a Token: Send a POST request to the login endpoint and retrieve the JWT token.
  2. Access Protected Routes:
    • Include the token in the Authorization header as:
      Authorization: Bearer <your_token>
    • Test secure endpoints with Postman or cURL.

 

Best Practices for JWT Authentication
 

  1. Keep Your Secret Key Safe: Store your secret key securely and avoid hardcoding it in your source code.
  2. Set Token Expiration: Use short-lived tokens to reduce the impact of token theft.
  3. Use Refresh Tokens: Implement a mechanism to issue new tokens without requiring the user to log in again.
  4. Handle Token Revocation: Maintain a blacklist of revoked tokens if necessary.

 

Conclusion
 

Implementing JWT authentication in CodeIgniter helps secure your REST API with a robust, stateless solution. By following the steps outlined in this guide, you can safeguard sensitive data and control access to your resources. In the next blog, we’ll discuss optimizing performance in REST  APIs built with CodeIgniter.

 

 

   

 

Recent Posts