All jobs

Add API Key Authentication to a Slim 4 App

Yes. An agent adds a PSR-15 middleware that checks an API key header on your Slim 4 route groups, with hashed keys in settings and 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 how the skeleton is wired before adding a middleware. In an app laid out like slimphp/Slim-Skeleton, public/index.php builds a PHP-DI container from app/settings.php, app/dependencies.php and app/repositories.php, creates the app with AppFactory, registers app/middleware.php, then app/routes.php, and installs an HttpErrorHandler that renders every HttpException as a JSON ActionError payload. The routes are a / hello, a /users group with ListUsersAction and ViewUserAction, and an OPTIONS /{routes:.*} handler for CORS pre-flight. The only middleware is SessionMiddleware, a PSR-15 class that reads $_SERVER['HTTP_AUTHORIZATION'] and starts a session, never checking the value. app/settings.php returns a Settings object with displayErrorDetails, logError and a logger block, so there is already one place for configuration that the tests in tests/TestCase.php load the same way index.php does. composer.json requires slim/slim ^4.12, php-di/php-di ^6.4 and monolog/monolog ^2.9 on PHP 7.4 or 8, with PHPUnit 9.6, PHPStan level 4 over src/ and phpcs on PSR-12, all run by .github/workflows/tests.yml on PHP 7.4 through 8.2.

The keys live in settings, hashed. The agent adds an apiKeys entry to app/settings.php with the header name (X-Api-Key) and a list of SHA-256 hashes read from an API_KEY_HASHES environment variable (comma separated), so no plain key is ever in the repository or the container, and a bin/make-api-key.php script that prints a random key and its hash for an operator to store. An ApiKeyMiddleware in src/Application/Middleware/ implements MiddlewareInterface like SessionMiddleware does, but reads the header from the PSR-7 request with getHeaderLine, hashes the value with hash('sha256', ...), compares it against each configured hash with hash_equals, and on a miss throws Slim's HttpUnauthorizedException, which the existing error handler renders as the standard JSON error with status 401. On a hit it attaches the matching key's label as an apiKey request attribute and logs the request through the injected LoggerInterface, which PHP-DI autowires from app/dependencies.php.

The middleware is added per group, not globally: in app/routes.php the /users group gets ->add(ApiKeyMiddleware::class), so / stays open and the OPTIONS catch-all keeps answering pre-flight requests, which browsers send without custom headers. SessionMiddleware is left as it is and the pull request notes that it reads a header the API key does not use. The agent keeps PHPStan happy at level 4 by typing the settings array it reads and the attribute it sets, and keeps phpcs happy by following the PSR-12 layout the other middleware already has.

The tests follow the skeleton's own pattern in tests/Application/Actions/User/ListUserActionTest.php: a new case sends GET /users with no header and asserts 401 with the ActionError payload the handler produces, one sends a wrong key and asserts the same, and one sends a key whose hash the test settings carry and asserts the existing 200 payload. A tests/Application/Middleware/ApiKeyMiddlewareTest.php checks the comparison with a mocked handler. The agent runs vendor/bin/phpcs, vendor/bin/phpstan and vendor/bin/phpunit on PHP 8.2 and on 7.4, the two ends of the workflow's matrix, before opening the pull request.

Start it with one API call

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

{
  "agent": "claude",
  "input": "Add API key authentication to this Slim 4 app. Read public/index.php, app/settings.php, app/dependencies.php, app/middleware.php, app/routes.php, src/Application/Actions/Action.php, src/Application/Handlers/HttpErrorHandler.php, src/Application/Middleware/SessionMiddleware.php, tests/TestCase.php, tests/Application/Actions/User/ListUserActionTest.php, composer.json and .github/workflows/tests.yml first. Add an apiKeys entry to app/settings.php with the header name X-Api-Key and SHA-256 hashes read from an API_KEY_HASHES environment variable, and a bin/make-api-key.php script that prints a random key and its hash. Write ApiKeyMiddleware as a PSR-15 middleware that reads the header from the request, hashes the value, compares with hash_equals against each configured hash, throws HttpUnauthorizedException on a miss, and sets an apiKey request attribute and logs on a hit. Add it to the /users group only. Extend ListUserActionTest with a missing-key, a wrong-key and a valid-key case, and add ApiKeyMiddlewareTest. Run vendor/bin/phpcs, vendor/bin/phpstan and vendor/bin/phpunit on PHP 8.2 and 7.4 until they pass, then open a pull request that lists which routes need a key and how an operator mints one.",
  "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 src/Application/Middleware/ApiKeyMiddleware.php, bin/make-api-key.php, the apiKeys settings entry, the route change in app/routes.php, and two test files. Its description lists the routes that now require a key (GET /users, GET /users/{id}) and the ones that stay open (/, OPTIONS), shows the 401 body as the skeleton's HttpErrorHandler renders it, and quotes the phpcs, phpstan and phpunit output from the sandbox on both PHP versions.

It documents the operator's path in three lines: run the script, store the printed key with the client, and put the printed hash in API_KEY_HASHES. Because the setting is a list, several clients can hold their own keys and one can be revoked by removing its hash, which the description says explicitly.

Before merging, a reviewer decides whether the key label should reach the actions (the apiKey attribute is there for it), whether SessionMiddleware should be removed now that nothing reads the session, and whether a per-key rate limit is wanted, which this change does not add.

Run it on every Linear issue labelled auth

An automation on the Project with a linear trigger on linear.issue.labeled, auth in config.labels, and the prompt "this issue names a route group that must require an API key or one that must stay open; adjust app/routes.php, extend the tests, and open a pull request" starts one run per labelled issue once the middleware exists. The trigger adds the issue after the prompt and fills in nothing else.

A team with several Slim services sends this body once per 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: a service with a database gets the hashes in a table with a last_used_at column instead of an environment variable, and one with an existing bearer-token middleware gets the key check added beside it as an alternative, not a replacement.

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

Why run it on Rush?

An API key check is short, and the short version is usually wrong somewhere: a plain key committed in a config file, a comparison with === that leaks timing, a header read from a superglobal that a reverse proxy strips, or a middleware added globally that breaks CORS pre-flight. The agent reads how the skeleton already handles settings, errors and middleware, fits the check into that shape, and proves it with the skeleton's own test harness on two PHP versions in its sandbox.

The static analysis, the code-style check and the test run stay with the run, so a reviewer sees the diff is clean at the repository's PHPStan level and that the missing, wrong and valid key paths are each asserted. A team with several PHP services runs the same request across all of them at once.

Frequently asked questions

Where are the keys stored?

Only as SHA-256 hashes, in the API_KEY_HASHES environment variable that app/settings.php reads. The plain key is printed once by bin/make-api-key.php and handed to the client; the repository, the container and the logs never hold it.

Why a header rather than a query parameter?

A query string ends up in access logs, browser history and referrer headers; a header does not. The name is configurable in settings, with X-Api-Key as the default, and the pull request shows the curl line a client uses.

Does the CORS pre-flight still work?

Yes. The OPTIONS /{routes:.*} handler in app/routes.php sits outside the /users group, and the middleware is added to the group, not to the app, so pre-flight requests, which carry no custom header, are answered without a key.

How does a client know the key was rejected?

The middleware throws HttpUnauthorizedException, and the skeleton's existing HttpErrorHandler renders it as the standard JSON ActionError payload with status 401. The new tests assert that status and shape for a missing and a wrong key.

More Slim jobs

The same job on other stacks

Keep reading