All jobs

Add JWT Authentication to a CodeIgniter 4 API

Yes. An agent adds a users table, a login route that issues a signed JWT, a filter that checks the Bearer token on API routes, feature tests, and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent reads the starter before it adds an endpoint. In an app laid out like codeigniter4/appstarter, composer.json requires PHP ^8.2 and codeigniter4/framework ^4.7, with phpunit/phpunit ^10.5.16, fakerphp/faker and vfsstream for development. app/Config/Routes.php defines one route, / to Home::index, and app/Controllers holds only BaseController and Home. app/Models, app/Database/Migrations and app/Database/Seeds are empty. app/Config/Filters.php aliases csrf, toolbar, honeypot, invalidchars, secureheaders, cors, forcehttps, pagecache and performance, and its $filters and $methods arrays are empty. app/Config/Database.php points the default group at MySQLi with no database name and the tests group at SQLite3 in memory; the env file shows every database.default.* key commented out. .github/workflows/phpunit.yml runs vendor/bin/phpunit --coverage-text on PHP 8.2 and 8.5 with the sqlite3 extension, and tests/ has unit/HealthTest.php, database/ExampleDatabaseTest.php and a _support tree with an example migration, seeder and model.

Two routes are open. Shield, the framework's own auth library (codeigniter4/shield 1.4.1, PHP ^8.2, on codeigniter4/settings), ships a JWT authenticator with a jwt filter and a JWTManager::generateToken() call, and brings users, sessions, groups and permissions with it. For an API that only needs a login and a token check, the agent takes the smaller route by default: firebase/php-jwt (7.2.1, PHP ^8.0) and about a hundred lines of its own, and the pull request names Shield as the choice for a team that also wants registration, password reset or groups.

The pieces land where the starter expects them. A migration CreateUsers in app/Database/Migrations creates users with id, email (unique), password_hash and timestamps. app/Models/UserModel.php lists email and password_hash as allowed fields, validates the email, and hashes a plain password in a beforeInsert callback with password_hash. app/Controllers/Api/Auth.php has login(): it validates email and password from the JSON body with the validation service, loads the user, checks password_verify, and answers {"token": ...} from JWT::encode with sub, iat and exp claims signed HS256 by a jwt.secret read from .env through env('jwt.secret'), with the lifetime from a new app/Config/Jwt.php. app/Filters/JwtAuth.php implements FilterInterface: before() reads the Authorization header, decodes the token with JWT::decode and new Key($secret, 'HS256'), puts the user id on the request for controllers, and returns a 401 JSON response on a missing, expired or badly signed token. It is aliased as jwt in Filters.php and applied with a route group: $routes->group('api', ['filter' => 'jwt'], ...) around a sample GET api/me, with POST api/login outside the group.

Tests use the framework's FeatureTestTrait and DatabaseTestTrait against the tests group, with $migrate = true and $namespace = 'App' so the new migration runs in the in-memory SQLite that CI already enables. One test logs in with a seeded user and asserts a token comes back, one calls api/me with that token and asserts the email, one sends no header and asserts 401, and one sends a token signed with another secret and asserts 401. The agent sets jwt.secret for the test run through phpunit.dist.xml's <env> entries, the same way the starter sets app.baseURL there, runs vendor/bin/phpunit until green, and adds jwt.secret to the env sample as a commented line with a note to generate a long random value.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add JWT authentication to this CodeIgniter 4 app with firebase/php-jwt. Read composer.json, app/Config/Routes.php, app/Config/Filters.php, app/Config/Database.php, env, phpunit.dist.xml, the tests directory and .github/workflows/phpunit.yml first. Add a CreateUsers migration (id, unique email, password_hash, timestamps), a UserModel that hashes a plain password in beforeInsert, an Api\\Auth controller with a login action that validates email and password from JSON, verifies the hash and returns a HS256 token with sub, iat and exp signed by jwt.secret from .env, with the lifetime in a new Config\\Jwt. Add an app/Filters/JwtAuth filter aliased as jwt that decodes the Bearer token and answers 401 JSON on a missing, expired or invalid one, and apply it with a route group around a sample GET api/me, keeping POST api/login outside it. Write feature tests on the tests database group with the migration enabled: login returns a token, api/me works with it, no header is 401, a token signed with another secret is 401. Set jwt.secret for tests in phpunit.dist.xml, add a commented jwt.secret line to env, run vendor/bin/phpunit until green, and open a pull request that quotes the test output and lists every new file.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

The pull request adds the migration, UserModel, Config\Jwt, the Api\Auth controller, the JwtAuth filter and a test class, and changes composer.json, composer.lock, app/Config/Routes.php, app/Config/Filters.php, phpunit.dist.xml and env. Its description quotes the phpunit output from the sandbox, shows one login request and one authenticated request with their JSON answers, and states the token lifetime and the claim set.

A reviewer checks the filter first: that it reads only the Authorization header, that an expired token and a bad signature both end in 401 and not 500, and that the group in Routes.php covers every route that should be private. Then the model, to confirm password_hash never leaves the API in a response, and the env note, to make sure the secret is generated rather than copied from the example.

From then on a new private endpoint is a route inside the api group, and the filter hands it the user id without any further code.

Run it on every new CodeIgniter service

A team that starts each service from the same starter sends this body once per new repository from its own server, each POST /o/{org}/sessions with that repository in resources and a request_id that is a UUID v5 of the repository's full name, so a retried call returns the run already started. Each run reads its own app: one that already has a users table gets the login wired to it, and one on MySQL in CI instead of SQLite gets tests against that group.

A small handler on the reader's server can receive GitHub's organization repository event, check its signature, and send this body for every repository created from the starter template. GitHub cannot add the Authorization: Bearer header a Rush webhook trigger requires, so the handler sends the request itself, with a request_id that is a UUID v5 of the delivery id so GitHub's redeliveries return the run already started.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

The mistakes in a hand-rolled JWT layer are the ones a reviewer rarely catches by reading: a filter that returns the exception message with a 500, a secret that is the example string, a route left outside the group. The agent writes the four feature tests first, runs them against the in-memory database the project's CI already uses, and keeps every command and its output with the pull request, so the 401 paths have been exercised before anyone reviews them.

A reviewer reads a filter, a controller and a test file instead of a tutorial. A team that spins up many services from the same starter starts the same request across all of them at once.

Frequently asked questions

Why not Shield?

Shield is the framework's own library and ships a JWT authenticator with a jwt filter and JWTManager::generateToken(). It also brings users, groups, permissions and settings tables. The agent picks the smaller firebase/php-jwt route for an API that needs a login and a check, and the pull request names Shield for a team that wants the rest; the prompt can ask for Shield instead.

Where does the secret live?

In .env as jwt.secret, read with env(), with a commented line in the env sample and a note to generate a long random value. The tests get their own value from phpunit.dist.xml, so no secret is committed.

Does it handle token expiry and refresh?

Expiry yes: the token carries exp from Config\Jwt, and the filter answers 401 when the library reports it expired. Refresh tokens are not part of this change; the pull request says where a refresh endpoint would go.

Will the tests run in CI?

Yes. The workflow installs the sqlite3 extension and the tests database group is SQLite in memory, so the migration-backed feature tests run on PHP 8.2 and 8.5 without a database server.

More CodeIgniter jobs

The same job on other stacks

Keep reading