Codeigniter 6: Authentication and Authorization for REST APIs in CodeIgniter
Securing your API is essential to protect sensitive data and ensure that only authorized users can access certain resources. CodeIgniter provides flexibility to implement various authentication and authorization mechanisms. In this blog, we’ll explore basic authentication, API keys, and token-based authentication using JSON Web Tokens (JWT).
Why Secure Your API?
Data Protection: Prevent unauthorized access to sensitive information.
Integrity: Ensure the data sent and received hasn’t been tampered with.
Access Control: Grant specific permissions to different users or roles.
Method 1: Basic Authentication
Basic authentication involves sending a username and password in the request header.
Set Up Middleware: Create a middleware to handle basic authentication.
namespace App\Filters; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\Filters\FilterInterface; class BasicAuth implements FilterInterface { public function before(RequestInterface $request, $arguments = null) { $authHeader = $request->getHeaderLine('Authorization'); if (!$authHeader || !preg_match('/Basic\s+(.*)$/i', $authHeader, $matches)) { return Services::response()->setJSON(['error' => 'Unauthorized'])->setStatusCode(401); } $credentials = base64_decode($matches[1]); list($username, $password) = explode(':', $credentials, 2); if ($username !== 'admin' || $password !== 'password') { return Services::response()->setJSON(['error' => 'Invalid credentials'])->setStatusCode(403); } } public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { // No action needed after the request } }
Register Middleware: Add the filter in
app/Config/Filters.php
:public $aliases = [ 'basicAuth' => \App\Filters\BasicAuth::class, ];
Apply Middleware: Use the filter in your routes:
$routes->group('secure', ['filter' => 'basicAuth'], function($routes) { $routes->get('users', 'UserController::index'); });
Method 2: API Key Authentication
API keys are unique identifiers passed in requests to authenticate users.
Generate API Keys: Store API keys in a database and associate them with users or clients.
Validate API Keys: Add validation logic in your controller or middleware:
$apiKey = $this->request->getHeaderLine('X-API-Key'); if (!$this->isValidApiKey($apiKey)) { return $this->failUnauthorized('Invalid API Key'); }
Secure Endpoints: Require API keys for sensitive operations.
Method 3: Token-based Authentication with JWT
JWT is a popular method for stateless authentication.
Install JWT Library: Use Composer to install a JWT library:
composer require firebase/php-jwt
Generate Tokens: Create a method in your controller to issue tokens:
use Firebase\JWT\JWT; use Firebase\JWT\Key; public function login() { $payload = [ 'iss' => 'localhost', 'sub' => 'user_id', 'iat' => time(), 'exp' => time() + 3600, ]; $token = JWT::encode($payload, 'your_secret_key', 'HS256'); return $this->respond(['token' => $token]); }
Validate Tokens: Add a middleware or logic to validate tokens:
try { $decoded = JWT::decode($token, new Key('your_secret_key', 'HS256')); } catch (Exception $e) { return $this->failUnauthorized('Invalid Token'); }
Conclusion
By implementing authentication and authorization, you can enhance the security of your REST API and control access to your resources. In the next blog, we’ll explore how to handle JSON input and output effectively in CodeIgniter REST APIs.