# Add JWT Authentication to a Ktor API

Yes. An agent adds a login route and JWT bearer auth to your Ktor API, protects the write routes, writes testApplication tests for tokens, and opens a PR.

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

## What the agent does

The agent reads the API before it adds a lock. In a service shaped like the `postgres` sample of ktorio/ktor-samples, `build.gradle.kts` applies `kotlin("jvm") 2.4.20`, `io.ktor.plugin 3.6.0` and the serialization plugin, depends on `ktor-server-core-jvm`, `ktor-server-content-negotiation-jvm`, `ktor-serialization-kotlinx-json-jvm`, `ktor-server-netty-jvm`, `ktor-server-config-yaml`, `postgresql 42.7.8` and `logback-classic`, has `ktor-server-test-host-jvm` and `kotlin-test-junit` for tests, and targets JVM 17 on the Gradle 9.2.1 wrapper. `src/main/resources/application.yaml` loads `com.example.PostgresApplicationKt.module` on port 8080. `PostgresApplication.kt` calls `configureSerialization()` and `configureRouting(connectToPostgres(embedded = false))`, and `connectToPostgres` reads the database name, user and password out of `postgres.yaml` with `YamlConfig`, the same file `docker-compose.yaml` extends for its `postgres:18.0-alpine` service.

`plugins/Routing.kt` registers `POST /articles`, which answers 201 with the new id, and `GET`, `PUT` and `DELETE /articles/{id}`, each wrapping `ArticleService`, a class that holds one JDBC `Connection`, creates the `ARTICLES` table in its `init` block and runs prepared statements inside `withContext(Dispatchers.IO)`. `models/Article.kt` is a `@Serializable data class Article(val title: String, val body: String)`. There is no `src/test` directory and no authentication dependency. The same repository has the pattern to follow: `jwt-auth-tests` installs `Authentication` with `jwt("auth-jwt")`, a `verifier`, a `validate` block that turns a `username` claim into a `JWTPrincipal`, a `challenge` that answers 401, a `POST /login` that signs a token with issuer, audience and a one-minute expiry, and an `authenticate("auth-jwt")` block around the protected route, with `ApplicationTest.kt` driving it through `testApplication` and `MapApplicationConfig`.

The agent adds `ktor-server-auth` and `ktor-server-auth-jwt`, a `configureSecurity()` function that installs the plugin with an HMAC verifier built from a `jwt.secret` entry in `application.yaml` that reads the `JWT_SECRET` environment variable, plus `jwt.issuer`, `jwt.audience` and `jwt.realm`, and a `POST /login` that takes a `@Serializable` user, checks it against a credentials store the reader points at (the sample has no users table, so the first version reads one admin user from configuration and the pull request says where to replace it), and returns a signed token. `POST`, `PUT` and `DELETE /articles` move inside `authenticate`, `GET /articles/{id}` stays public, and the route handlers read the principal's `username` claim so a later audit column has it.

For tests the agent mirrors `jwt-auth-tests`: a `testApplication` with `MapApplicationConfig` for the secret, issuer and audience, an `application { configureSecurity(); routing { authenticate("auth-jwt") { get("/protected") { call.respondText("ok") } } } }` block, and cases for no token (401 with the challenge body), a token signed with another secret (401), an expired token (401), a valid token (200), and the login round trip. Those run without Postgres, because `configureRouting` takes the `Connection` and is not called. The agent runs `./gradlew test` and `./gradlew build` in the sandbox and keeps the output; the repository's `build-all.sh` runs the same for every sample on a 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 Ktor API and open a pull request. Read build.gradle.kts, gradle.properties, src/main/resources/application.yaml, postgres.yaml, src/main/kotlin/com/example/PostgresApplication.kt, plugins/Routing.kt, service/ArticleService.kt and models/Article.kt first, and the jwt-auth-tests sample in this repository for the pattern. Add ktor-server-auth and ktor-server-auth-jwt, a configureSecurity function that installs Authentication with an HMAC verifier using jwt.secret from application.yaml read from the JWT_SECRET environment variable, plus jwt.issuer, jwt.audience and jwt.realm, a validate block that requires a username claim, and a challenge that answers 401. Add POST /login that checks a username and password against one admin user read from configuration, with a comment and a note in the pull request on where a real user store goes, and returns a signed token with an expiry. Wrap POST /articles, PUT /articles/{id} and DELETE /articles/{id} in authenticate and leave GET /articles/{id} public. Add src/test with testApplication cases for no token, a token with the wrong secret, an expired token, a valid token and the login round trip, using MapApplicationConfig and a small protected test route so Postgres is not needed. Run ./gradlew test and ./gradlew build and paste the output in the pull request. Do not change ArticleService or the database setup.",
  "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 two dependencies to `build.gradle.kts`, a `jwt` block to `application.yaml`, a `plugins/Security.kt` with `configureSecurity` and the login route, a few lines in `Routing.kt` that move the three write routes inside `authenticate`, one line in `PostgresApplication.kt`, and a new `src/test/kotlin/com/example/SecurityTest.kt`. The description pastes the Gradle test summary and names the `JWT_SECRET` variable the service now needs at start.

The repository's `build-all.yml` runs `build-all.sh` on the pull request, which builds and tests every sample, so the new tests run there with the same JDK the workflow sets up.

A reviewer starts the service with `./gradlew run` and the compose database, posts to `/login`, and confirms that a `POST /articles` without the token answers 401 and with it answers 201 as before. They check the expiry, that `GET /articles/{id}` is still open, and where the admin credentials come from. Then they merge and set `JWT_SECRET` in each environment.

## Run it on every API with open write routes

A team with several Ktor services sends one `POST /o/{org}/sessions` per repository with this prompt and the repository in `resources`. Each run reads its own routes, so a service that already has a users table gets `POST /login` checking against it instead of configuration, and each opens its own pull request.

Give the key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with `session_url` to read the pull request from, so the secrets to set per environment can be collected from each description.

## Why run it on Rush?

Authentication is where a half-tested change is worst: a verifier that accepts the wrong secret, an expiry nobody checked, a route left outside `authenticate`. In a Rush sandbox the agent runs the five token cases and the login round trip through `testApplication` before pushing, and the Gradle output stays in the run's record beside the pull request.

The change spans a build file, configuration, a new plugin function, the router and a new test directory. The agent does it in one pass, following the JWT sample already in the repository, and the same request works unchanged on the next service whose write routes are open.

## Frequently asked questions

### Why HMAC and not the RSA and JWKS setup from jwt-auth-tests?

Because the sample serves its own `jwks.json` for a single issuer, which is more moving parts than one service needs. An HMAC secret from `JWT_SECRET` is one configuration value; the pull request notes what changes if tokens must be verified by other services.

### Where do the users come from?

The `postgres` sample has an `ARTICLES` table and nothing else, so the first version reads one admin username and password from configuration and marks the spot. A run on a service with a users table checks against that table instead.

### Do the tests need the database?

No. `configureRouting` takes the JDBC `Connection` as a parameter and the tests never call it; they install `configureSecurity` and a small protected route inside `testApplication`, so `./gradlew test` passes without Postgres.

### Is GET still public?

Yes. Only `POST /articles`, `PUT /articles/{id}` and `DELETE /articles/{id}` move inside `authenticate`, which the prompt states, and a test reads an article without a token to prove it.

## More Ktor jobs

- [Add OpenAPI Docs to a Ktor Server](https://getrush.ai/run/add-openapi-docs/ktor/)
- [Add OpenTelemetry Tracing to a Ktor Server](https://getrush.ai/run/add-opentelemetry/ktor/)
- [Add Prometheus Metrics to a Ktor Server](https://getrush.ai/run/add-prometheus-metrics/ktor/)

## The same job on other stacks

- [Add JWT Auth to a Quarkus API](https://getrush.ai/run/add-jwt-auth/quarkus/)
- [Add JWT Authentication to a Vapor App from a Linear Issue](https://getrush.ai/run/add-jwt-auth/vapor/)
- [Add JWT Authentication to an Actix Web API](https://getrush.ai/run/add-jwt-auth/actix/)

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