How does CI4 handle RESTful API authentication?

Why Interviewers Ask This

This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.

Answer

CI4 RESTful API authentication is typically implemented using Filters. Common approaches: API Key authentication: client passes a key in the X-API-Key header; a filter validates it against the database. JWT (JSON Web Tokens): use a Composer package like lcobucci/jwt or firebase/php-jwt. The filter decodes and validates the JWT from the Authorization: Bearer {token} header. CodeIgniter Shield tokens: Shield's token auth handler validates tokens from the Authorization header. HTTP Basic Auth: CI4's IncomingRequest provides getServer("PHP_AUTH_USER") and getServer("PHP_AUTH_PW"). In the Filter's before() method, reject the request: return Services::response()->setStatusCode(401)->setJSON(["error" => "Unauthorized"]). Always use HTTPS for API auth — never send credentials over plain HTTP.

Common Mistake

Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real CodeIgniter project.