# Add Logout That Revokes a JWT in FastAPI

Yes. An agent adds a jti claim with PyJWT, a revoked-token table and migration, a logout endpoint and a check on every request, tests it and opens a PR.

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

## What the agent does

The agent reads how a token is made and checked. In a FastAPI app laid out like fastapi/full-stack-fastapi-template, `backend/app/core/security.py` builds the access token with `jwt.encode({"exp": expire, "sub": str(subject)}, settings.SECRET_KEY, algorithm="HS256")`, `ACCESS_TOKEN_EXPIRE_MINUTES` in `backend/app/core/config.py` is eight days, and `get_current_user` in `backend/app/api/deps.py` decodes the token into `TokenPayload`, whose only field is `sub`, then loads the `User` row and refuses an inactive one. Logging out is a browser-side act: `logout` in `frontend/src/hooks/useAuth.ts` removes `access_token` from `localStorage` and navigates to `/login`. The token itself stays valid until it expires, so a copied token, or a session on a lost laptop, keeps working for up to eight days after the person has signed out.

The token gets an identity. `create_access_token` adds a `jti` claim, a `uuid4` string, and an `iat`, and `TokenPayload` in `backend/app/models.py` gains `jti: str | None = None` and `exp: int | None = None`, so the decoded payload still validates for tokens issued before the change. A new table-backed model `RevokedToken` holds `jti` as its primary key and `expires_at`, and the agent generates the migration with `alembic revision --autogenerate`, since `backend/app/alembic/env.py` points `target_metadata` at `SQLModel.metadata` and sets `compare_type=True`; the new file's `down_revision` is `fe56fa70289e`, the current head. `get_current_user` then does one primary-key lookup: a token whose `jti` is in the table is refused with the same `403` and `Could not validate credentials` message an invalid token gets, so the client code in `frontend/src/main.tsx`, which clears the token and redirects to `/login` on a 401 or 403 from any query or mutation, needs no change.

A `POST /login/logout` route goes beside `login_access_token` in `backend/app/api/routes/login.py`. It depends on `CurrentUser` and on the raw token through `TokenDep`, decodes it, inserts its `jti` with its `exp` as `expires_at`, and deletes rows whose `expires_at` has passed, so the table never grows past the number of logouts in one expiry window. A token with no `jti` is accepted by the check and cannot be revoked; the agent keeps that behaviour on purpose, so sessions issued before the deploy keep working until they expire, and writes it into the route's docstring and the pull request. On the frontend, `scripts/generate-client.sh` regenerates `frontend/src/client` from the OpenAPI document, which the `generate-frontend-sdk` pre-commit hook also does on any change under `backend/app`, and `logout` in `useAuth.ts` calls the new `LoginService.logout()` before removing the stored token, ignoring a failure so a dead API never traps a user in a signed-in state.

Tests follow `backend/tests/api/routes/test_login.py`, which already covers the bcrypt-to-argon2 upgrade on login with the `client` and `db` fixtures from `backend/tests/conftest.py`. New tests log in, call `/login/logout`, then call `/login/test-token` with the same header and expect a 403; call logout twice and expect the second to be harmless; and build a token with `jwt.encode` and no `jti` to show it still passes. The agent installs Docker with `sudo apt-get install -y docker.io` and the Compose v2 plugin, which that package does not include, starts `dockerd` and brings up the compose database, then runs `bash scripts/test.sh`, which is `coverage run -m pytest tests/` against it, and `bash scripts/lint.sh`, which is `mypy`, `ty check`, `ruff check` and `ruff format --check`, since `pyproject.toml` sets `strict = true` for mypy and `error-on-warning` for ty. The `Test Backend` workflow also requires `coverage report --fail-under=90`, so the new route and the sweep both get a test rather than a comment.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Add logout that revokes the access token. Read backend/app/core/security.py, backend/app/api/deps.py, backend/app/api/routes/login.py, backend/app/models.py, backend/app/alembic/env.py, backend/tests/api/routes/test_login.py, frontend/src/hooks/useAuth.ts and frontend/src/main.tsx first. Add jti and iat claims to the token, a RevokedToken table with an autogenerated Alembic migration, a POST /login/logout route that stores the token's jti and deletes expired rows, and a check in get_current_user that refuses a revoked token with the existing 403 message. Tokens without a jti stay valid until they expire; say so in the docstring. Regenerate the frontend client and call the route from logout in useAuth.ts. Add tests for logout, a second logout and an old token, run scripts/test.sh and scripts/lint.sh, quote the results and 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 changes `backend/app/core/security.py`, `backend/app/api/deps.py`, `backend/app/api/routes/login.py` and `backend/app/models.py`, adds one migration under `backend/app/alembic/versions/`, regenerates `frontend/src/client`, and changes `frontend/src/hooks/useAuth.ts`. The new tests sit in `backend/tests/api/routes/test_login.py` beside the existing login tests.

The description holds the pytest summary with the coverage table that `scripts/test.sh` prints, the four lint commands and their output, the migration's `upgrade` and `downgrade` bodies, and a short list of the decisions: the same 403 for revoked and invalid tokens, pre-change tokens left valid, and the expired-row sweep run from the logout route rather than a scheduler. The repository's `Test Backend`, `Playwright Tests` and `pre-commit` workflows run on the branch.

Before merging, a reviewer decides whether changing a password in `update_password_me` should also revoke the person's other tokens, which the new table makes a two-line change, and whether eight days of `ACCESS_TOKEN_EXPIRE_MINUTES` is still the right window now that a token can be ended early. The agent leaves both as they are and names them.

## Run it on every Linear issue labelled auth

In the Project that holds the repository, create an automation with a general form of this page's prompt and a `linear` trigger on `linear.issue.labeled` with `auth` in its `labels`, and the team key in `teams` if only one team's issues should start runs. The issue is placed after the prompt and fills in nothing, so the prompt says to read the issue that follows, make the change it describes to the token or login code, keep the test and lint scripts green and open a pull request that names the issue.

A product manager who files the issue after a customer asks why signing out did not end a session on another device gets a pull request back with the tests in it. A later issue under the same label, say a shorter expiry for admin accounts, starts its own run, and the automation's `max_runs_per_hour` bounds how many such runs start in an hour.

## Why run it on Rush?

A revocation change touches the token format, a migration, a route, the generated client and the frontend's logout, and the only honest proof is the whole backend suite against a real Postgres plus the strict type checks the repository enforces. The sandbox brings up the compose database, runs the migration and the tests, and keeps the output, so the pull request opens with the evidence rather than a note to run the suite locally.

The run's record shows the exact `jwt.decode` behaviour the agent checked, the migration it generated and every test it ran, so a reviewer reads reasons instead of trusting a summary. Across several services built on this template the same request runs at once, one sandbox each, with each pull request fitted to that service's own routes and tests.

## Frequently asked questions

### Does every request now hit the database twice?

`get_current_user` already loads the `User` row by primary key on every request. The revocation check is one more primary-key lookup on a small table, and the sweep in the logout route keeps that table at most one expiry window long.

### Why not keep the revoked ids in memory or in Redis?

The template runs `fastapi run --workers 4` in its Dockerfile, so an in-memory set would differ per worker and a logout would only take effect on one of them. The compose file has Postgres and no Redis, so a table is the store every worker already shares.

### What happens to people who are signed in when this deploys?

Their tokens have no `jti`, so the check accepts them and they stay signed in until the token expires. Signing out and in again gives them a token that can be revoked. If the team would rather force everyone out, rotating `SECRET_KEY` does that in one step.

### Why the same error message for a revoked token?

`frontend/src/main.tsx` treats any 401 or 403 from a query or mutation as a sign-out and redirects to `/login`, so the client already does the right thing. A distinct message would only tell an attacker which tokens were revoked on purpose.

## More PyJWT jobs

- [Fix "DecodeError: It is required that you pass in a value for the 'algorithms' argument" in PyJWT](https://getrush.ai/run/fix-jwt-decode-algorithms-argument-required/pyjwt/)
- [Upgrade PyJWT From 1.x to 2.x in a Flask API](https://getrush.ai/run/upgrade-pyjwt/pyjwt/)

## More jobs like this: Turn a Linear label into a PR

- [Show Token Usage per Reply in a Streamlit Chat App](https://getrush.ai/run/add-token-usage-display/streamlit/)
- [Track Token Usage per User in an AI SDK Chatbot](https://getrush.ai/run/add-token-usage-tracking/ai-sdk/)
- [Wrap Multi-Step Writes in Transactions with Drizzle](https://getrush.ai/run/add-transactions/drizzle/)
- [Add Transactions to a Mongoose App](https://getrush.ai/run/add-transactions/mongoose/)

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