# Add JWT Authentication to a Litestar App

Yes. An agent adds Litestar's built-in JWTAuth to your app with a login handler, a user lookup, protected routes, typed tests and a mypy-clean diff, and opens a PR.

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

## What the agent does

The agent reads the app and its tooling first. In a project laid out like litestar-org/litestar-hello-world, `app.py` is the whole application: two handlers, `GET /async` and `GET /sync` (the latter with `sync_to_thread=False`), each returning `{"hello": "world"}`, registered on a `Litestar` instance. `pyproject.toml` depends on `litestar[standard]>=2.4.1`, which `pdm.lock` resolves to 2.4.1, supports Python 3.8 through 3.12, and runs `pytest` with `asyncio_mode = "auto"`; `tests/test_app.py` has two tests that use `litestar.testing.TestClient` against the imported `app`. Linting is a `pre-commit` set in `.pre-commit-config.yaml` with Ruff on `select = ["ALL"]` at line length 120, mypy in `strict` mode with `litestar[standard]` as an additional dependency, codespell, slotscheck and pyright, and `.github/workflows/ci.yaml` runs `pre-commit run --all-files` and then the test matrix on 3.8 to 3.11 through PDM.

Litestar ships JWT support in `litestar.security.jwt`, so no new dependency is added beyond `litestar[jwt]`, which brings `python-jose` through the extra. The agent moves the app into a small package layout the tests already allow for (`app.py` keeps `app` importable), adds a `User` dataclass and an in-memory `USERS` mapping with hashed passwords, and a `retrieve_user_handler` coroutine that takes the decoded `Token` and the `ASGIConnection` and returns the user for `token.sub` or `None`. The `JWTAuth[User]` instance is built with that handler, `token_secret` read from a `JWT_SECRET` environment variable (failing at import if unset outside tests), `default_token_expiration` as a `timedelta`, and `exclude=["/login", "/schema"]` so the login route and the OpenAPI pages stay open; it is registered through `on_app_init=[jwt_auth.on_app_init]`, which also adds the bearer scheme to the OpenAPI document.

The login handler is `POST /login`, typed with a `LoginData` dataclass as `data`, which looks the user up, verifies the password with `hashlib` and `hmac.compare_digest`, and returns `jwt_auth.login(identifier=user.id, response_body=user)`, so the token arrives in the `Authorization` header and the user in the body. `/async` and `/sync` become protected simply because they are not excluded, and the agent changes them to take `request: Request[User, Token, State]` and return the caller's name beside `hello`, which demonstrates the typed access Litestar gives a handler. A `/me` route returns the user from the token. The type annotations keep mypy in `strict` mode happy, and `__all__` is updated because the `ensure-dunder-all` hook checks it.

The tests extend `tests/test_app.py` in the same `TestClient` style: `/sync` without a header expects `401`, a `POST /login` with a known user expects `201` and an `Authorization` header starting with `Bearer`, and that header on `/sync` and `/me` expects `200` with the user's name; a tampered token expects `401`. The agent runs `pdm install`, `pre-commit run --all-files` (Ruff, mypy strict, pyright, slotscheck, codespell) and `pdm run pytest` on Python 3.11 and 3.8, since 3.8 is the floor in `requires-python`, before opening the pull request.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add JWT authentication to this Litestar app. Read app.py, pyproject.toml, pdm.lock, tests/test_app.py, .pre-commit-config.yaml, Makefile and .github/workflows/ci.yaml first. Add the litestar[jwt] extra to pyproject.toml and update pdm.lock. Add a User dataclass, an in-memory USERS mapping with hashed passwords, and a retrieve_user_handler coroutine that returns the user for token.sub or None. Build a JWTAuth[User] with that handler, token_secret from JWT_SECRET, a default_token_expiration timedelta and exclude for /login and /schema, and register it with on_app_init. Add POST /login taking a LoginData dataclass, verifying the password with hmac.compare_digest and returning jwt_auth.login with the user as response body; add GET /me returning the user from the token; change /async and /sync to take Request[User, Token, State] and include the caller's name. Keep __all__ current. Extend tests/test_app.py for 401 without a header, 201 with a Bearer header on login, 200 on /sync and /me with the token, and 401 for a tampered token. Run pdm install, pre-commit run --all-files and pdm run pytest on Python 3.11 and 3.8 until they pass, then open a pull request listing which routes require a token and which stay open.",
  "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 changes `app.py`, `pyproject.toml`, `pdm.lock` and `tests/test_app.py`, and adds the user module beside the app. Its description lists the routes that now require a token (`/async`, `/sync`, `/me`) and the ones that stay open (`/login`, `/schema`), shows a sample `401` body as Litestar renders it, and quotes the `pre-commit` and `pytest` output from both Python versions in the sandbox.

It explains the two choices a reviewer will ask about: the secret comes from `JWT_SECRET` with no default in the code, and the OpenAPI document at `/schema` gains the bearer security scheme because `on_app_init` registers it, so the generated client code and the Swagger page already know how to send the token.

Before merging, a reviewer swaps the in-memory `USERS` mapping for the real user store, decides on the token lifetime and whether a refresh route is needed, and whether `JWTCookieAuth` would suit a browser client better than the header-based `JWTAuth`, which the pull request names as the one-line alternative.

## 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 or router that must require a bearer token, or one that must stay open; adjust the exclude list or the handler, extend the tests, and open a pull request" starts one run per labelled issue once the login route exists. The trigger adds the issue after the prompt and fills in nothing else, so a new `/admin` router is protected and a new health route is excluded by the same mechanism.

A team with several Litestar 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 SQLAlchemy models gets the lookup against its user table, and one that already uses `OAuth2PasswordBearerAuth` gets only the tests and the typed request signatures.

## Why run it on Rush?

Litestar's JWT support is small and typed, and the mistakes are in the details: a secret with a default value in the source, a login route caught by its own guard, a handler whose `Request` generics do not match what the auth class provides so mypy in strict mode rejects the file, or a `__all__` the pre-commit hook refuses. The agent fits the change to the repository's own hooks and runs them, with the full test suite, on both ends of the supported Python range in its sandbox.

The hook output, the test run and the diff stay with the run, so a reviewer sees that Ruff with every rule on, mypy strict and pyright all pass, and that each route's behaviour with and without a token is asserted. A team with several Python services runs the same request across all of them at once.

## Frequently asked questions

### Does this add a third-party auth library?

No. `JWTAuth` lives in `litestar.security.jwt`, and the `litestar[jwt]` extra pulls in the JOSE library it uses. The app keeps one framework dependency, and the `pdm.lock` update is the only dependency change.

### Where does the user come from?

From the `retrieve_user_handler` coroutine, which Litestar calls with the decoded token on every protected request. In the starter it looks up an in-memory mapping; in a real service it queries the user store. The handler's return type is what makes `Request[User, Token, State]` typed in every protected handler.

### Will the OpenAPI page still open without a token?

Yes. `/schema` is in the `exclude` list beside `/login`, and `on_app_init` adds the bearer scheme to the document, so the Swagger and Redoc pages at `/schema` show an Authorize button and the generated spec declares which routes need the token.

### What about Python 3.8?

`requires-python` starts at 3.8, so the agent runs the hooks and tests there as well as on 3.11. The dataclasses and `typing` imports are chosen to work on both, and the pull request quotes both runs.

## More Litestar jobs

- [Add OpenTelemetry Tracing to a Litestar App](https://getrush.ai/run/add-opentelemetry/litestar/)
- [Add Prometheus Metrics to a Litestar App](https://getrush.ai/run/add-prometheus-metrics/litestar/)
- [Add Rate Limiting to a Litestar API](https://getrush.ai/run/add-rate-limiting/litestar/)

## The same job on other stacks

- [Add JWT Authentication to a Slim 4 API](https://getrush.ai/run/add-jwt-authentication/slim/)
- [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/)

## 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/)
