# Add JWT Authentication to a Slim 4 API

Yes. An agent adds a PSR-15 JWT middleware to your Slim 4 app, protects the /users routes, covers it with PHPUnit tests in the skeleton's own style, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-jwt-authentication/slim/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the skeleton's wiring before it adds a middleware, because Slim 4 gives three places to attach one and the error handling decides what a rejected request looks like. In an app like slimphp/Slim-Skeleton, `public/index.php` builds a PHP-DI container from `app/settings.php`, `app/dependencies.php` and `app/repositories.php`, then applies `app/middleware.php` and `app/routes.php`. The routes are an `OPTIONS` catch-all for CORS pre-flight, `GET /` and a `/users` group with `ListUsersAction` and `ViewUserAction`. `HttpErrorHandler` extends Slim's error handler and maps `HttpUnauthorizedException` to an `ActionError` of type `UNAUTHENTICATED` with the exception's status code, serialised as the same JSON `ActionPayload` the actions return. `composer.json` requires `slim/slim` `^4.12`, `slim/psr7` `^1.6`, `php-di/php-di` `^6.4` and `monolog/monolog` `^2.9` on `php ^7.4 || ^8.0`, with PHPUnit `^9.6.17`, PHPStan `^1.10` at level 4 and PHP_CodeSniffer on PSR-12; `composer.lock` is gitignored.

One existing middleware matters. `SessionMiddleware`, the only entry in `app/middleware.php`, calls `session_start()` whenever `$_SERVER['HTTP_AUTHORIZATION']` is set and attaches `$_SESSION` to the request. A `Bearer` header would make every API call open a PHP session, so the agent does not add JWT on top of that quietly: the pull request explains the overlap and removes the session start for Bearer requests, keeping the session behaviour for everything else, and asks you to confirm that is what you want.

The change adds `firebase/php-jwt` with `composer require`, a `jwt` block in `app/settings.php` with the secret read from the `JWT_SECRET` environment variable, the algorithm and the expected issuer, and `src/Application/Middleware/JwtAuthMiddleware.php` implementing `Psr\Http\Server\MiddlewareInterface`. It reads the `Authorization` header, requires the `Bearer` scheme, decodes with the configured key, and on any failure throws `HttpUnauthorizedException`, so the existing `HttpErrorHandler` renders the `UNAUTHENTICATED` payload with no new error code path. On success the decoded claims are attached as a `token` request attribute for actions to read. The middleware is registered in `app/dependencies.php` and attached with `->add(JwtAuthMiddleware::class)` on the `/users` group in `app/routes.php`, leaving `GET /` and the `OPTIONS` handler public. Minting tokens stays with your identity provider or login action; the tests sign their own.

Tests follow `tests/TestCase.php`: `getAppInstance()` rebuilds the container and routes, and `createRequest()` takes a headers array, so `['HTTP_AUTHORIZATION' => 'Bearer …']` is enough. `tests/Application/Middleware/JwtAuthMiddlewareTest.php` covers a missing header, a wrong scheme, a token signed with another key, an expired token and a valid one against `/users/1` with the `UserRepository` prophecy the existing `ViewUserActionTest` already uses, asserting the exact `ActionPayload` JSON. Because the error middleware is only added in `public/index.php`, the failure cases add `ErrorMiddleware` with `HttpErrorHandler` the way that existing test does. The agent installs PHP in its sandbox, runs `composer install`, `vendor/bin/phpunit`, `vendor/bin/phpstan` and `vendor/bin/phpcs`, the three commands `.github/workflows/tests.yml` runs, and includes the output.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add JWT authentication to this Slim 4 application. Read public/index.php, the app directory, the actions, the HttpErrorHandler, the existing middleware and the tests first. Add firebase/php-jwt, a jwt settings block whose secret comes from the JWT_SECRET environment variable, and a PSR-15 middleware that requires a Bearer token, verifies it and throws HttpUnauthorizedException on failure so the existing error handler renders the UNAUTHENTICATED payload; attach the decoded claims to the request. Protect the /users route group only. Explain and resolve the overlap with the existing SessionMiddleware, which starts a session whenever an Authorization header is present. Do not add a token-issuing endpoint. Write PHPUnit tests in the style of tests/TestCase.php for a missing header, wrong scheme, wrong key, expired token and a valid token, asserting the exact JSON payloads. Run phpunit, phpstan and phpcs as the workflow does and include the output. Open a pull request.",
  "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

What comes back is a pull request that adds `src/Application/Middleware/JwtAuthMiddleware.php` and `tests/Application/Middleware/JwtAuthMiddlewareTest.php`, changes `composer.json` (`firebase/php-jwt`), `app/settings.php` (the `jwt` block), `app/dependencies.php` (the middleware definition), `app/routes.php` (the group-level `add`) and `src/Application/Middleware/SessionMiddleware.php` (no session for Bearer requests), and documents `JWT_SECRET` in the README. No action class changes.

The description quotes the PHPUnit summary with the new tests named, the PHPStan level 4 result and the PSR-12 check, and explains the `SessionMiddleware` decision in a paragraph a reviewer can accept or reverse. The commands and full output are in the transcript at `GET /o/{org}/sessions/{id}/messages`; the `Tests` workflow runs the same three commands on the pull request across its PHP matrix.

Before merging, a reviewer sets `JWT_SECRET` in each environment, confirms the issuer and algorithm match the tokens your clients already carry, and decides whether `GET /` or any future route should also sit behind the middleware. A follow-up message to the same session can switch verification to a JWKS endpoint if your provider publishes one.

## Run it on every Slim service that still trusts every caller

A team with several Slim APIs starts one run per repository with one `POST /o/{org}/sessions` each, the repository in `resources` and this prompt as `input`, naming the route groups to protect. Each run reads its own `routes.php`, error handler and middleware stack, so a service with a different error payload shape gets a middleware that throws into that shape rather than a copied class.

Send a `request_id`, a UUID v5 of the repository's full name, so a retried call returns the run it already started. The key's `webhook_url` reports when each run the key starts finishes, with the run's final answer in `result`.

## Why run it on Rush?

Verifying a JWT is a library call; fitting it into a Slim app is the work: which group to attach to, how a failure becomes the same JSON error the API already speaks, what the session middleware does when an `Authorization` header appears, and how the test base class builds requests. The agent reads all of that and runs the skeleton's own PHPUnit, PHPStan and PHP_CodeSniffer commands in a sandbox of its own, with the output kept.

The pull request carries the test names, the static analysis result and the reasoning about the session overlap, so the review is a check of the security decisions, not a reconstruction of them. Several services can be done at once, each in its own sandbox with its own pull request.

## Frequently asked questions

### Will unauthenticated requests get the same error format?

Yes. The middleware throws `HttpUnauthorizedException`, which the skeleton's `HttpErrorHandler` already maps to an `ActionError` of type `UNAUTHENTICATED` inside the usual `ActionPayload` JSON with status `401`. No new response shape is introduced.

### Why change SessionMiddleware?

It calls `session_start()` whenever the `Authorization` header is present, which predates bearer tokens in this skeleton. Left alone, every token-bearing API call would create a server-side session. The agent keeps the session behaviour for non-Bearer requests, documents the change, and treats it as a decision for the reviewer.

### Does it issue tokens too?

No. The task is to verify tokens your identity provider or existing login flow issues; adding a login endpoint means choosing a user store and password handling, which is a separate change. The tests sign their own tokens with the test secret so they need no provider.

### Which PHP versions does it test on?

The agent runs the suite on one PHP version in its sandbox and reports it; the repository's `tests.yml` matrix then runs the same `phpunit`, `phpstan` and `phpcs` commands on each PHP version the project lists when the pull request opens.

## More Slim jobs

- [Add OpenAPI Docs to a Slim 4 App](https://getrush.ai/run/add-openapi-docs/slim/)
- [Add OpenTelemetry Tracing to a Slim 4 App](https://getrush.ai/run/add-opentelemetry/slim/)
- [Add Pagination to a Slim 4 List Endpoint](https://getrush.ai/run/add-pagination/slim/)

## The same job on other stacks

- [Add JWT Authentication to a Socket.IO Server](https://getrush.ai/run/add-jwt-authentication/socket-io/)
- [Add JWT Authentication to a CodeIgniter 4 API](https://getrush.ai/run/add-jwt-authentication/codeigniter/)
- [Add JWT Authentication to a Fiber API](https://getrush.ai/run/add-jwt-authentication/fiber/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
