All jobs

Add JWT Authentication to an Actix Web API

Yes. An agent adds a token route and a bearer extractor to your Actix Web app beside its cookie session, so API clients authenticate with a JWT, with tests, in 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 clones the repository into its own cloud sandbox and reads how a request is authenticated today before it adds a second way. In the auth/simple-auth-server member of actix/examples, src/main.rs wraps the app in IdentityMiddleware and a SessionMiddleware over CookieSessionStore keyed from utils::SECRET_KEY, with a one-day TTL, a cookie named auth-example and cookie_secure(false), and serves POST /api/invitation, POST /api/register/{invitation_id} and POST, DELETE and GET /api/auth. src/auth_handler.rs defines AuthData { email, password }, aliases LoggedUser to SlimUser, implements FromRequest for it by reading the Identity and deserialising the stored JSON, and in login runs a Diesel query on users, verifies the hash with utils::verify and calls Identity::login. src/utils.rs hashes with rust-argon2 using SECRET_KEY as the secret and a fixed salt, and SECRET_KEY itself falls back to "0123".repeat(16) when the environment variable is absent. src/errors.rs maps ServiceError::Unauthorized to a 401 JSON body.

The workspace shapes the dependency choice. The root Cargo.toml uses resolver 3, edition 2024 and rust-version = "1.98", and pins actix-web 4.11, actix-identity 0.9 and actix-session 0.11 as workspace dependencies; nothing named jsonwebtoken or actix-web-httpauth is there yet. The crate's own Cargo.toml adds Diesel 2 on Postgres with r2d2, uuid and chrono, rust-argon2 3, once_cell and temp-env. Its only test is secret_key_default in utils.rs. .github/workflows/ci.yml runs cargo check and cargo test across the workspace with libpq-dev installed but no Postgres server, and the justfile runs prettier, taplo and cargo +nightly fmt for formatting and cargo clippy --workspace --all-targets --all-features.

The agent adds jsonwebtoken and actix-web-httpauth to the workspace dependency table and to the crate, and writes src/jwt.rs: a Claims struct with sub (the email), iat and exp, encode and decode functions on HS256 with a JWT_SECRET read from the environment and kept separate from SECRET_KEY, because that value already seeds the argon2 hashing and the cookie key, and a Validation that requires exp with a small leeway. A new POST /api/token handler takes the same AuthData, runs the same query as login, and returns { access_token, token_type: "Bearer", expires_in }. The FromRequest impl for LoggedUser now tries BearerAuth first, decoding the token into a SlimUser, and falls back to the Identity path, so GET /api/auth serves both browser sessions and API clients, and a bad or expired token maps to ServiceError::Unauthorized.

Tests need no database for most of this. src/jwt.rs gets a round-trip test and an expired-token test under temp-env for the secret; auth_handler.rs gets an #[actix_web::test] that builds an App with the get_me route alone, sends a TestRequest with a valid Authorization: Bearer header and expects the SlimUser JSON, and another with a tampered token expecting 401. The login query still needs Postgres, which CI does not start for this crate, so that path is covered by the existing cookie flow and noted in the pull request. The agent runs cargo test -p simple-auth-server, cargo clippy --workspace --all-targets --all-features, the formatters the justfile names, and cargo check --workspace --bins --examples --tests as ci.yml does, and adds a curl sequence for the token flow to the crate's README.md.

Start it with one API call

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

{
  "agent": "claude",
  "input": "Add JWT authentication to the auth/simple-auth-server crate in this workspace and open a pull request. Read the root Cargo.toml, auth/simple-auth-server/Cargo.toml, every file under auth/simple-auth-server/src, its README.md, .github/workflows/ci.yml and the justfile first. Add jsonwebtoken and actix-web-httpauth as workspace dependencies. Write a jwt module with claims carrying the email, issued-at and expiry, HS256 signing with a JWT_SECRET environment variable separate from SECRET_KEY, and validation that requires expiry. Add POST /api/token that checks the same credentials as login and returns an access token with its type and lifetime. Make the LoggedUser extractor accept a bearer token first and fall back to the identity cookie so GET /api/auth works for both. Map bad tokens to the existing Unauthorized error. Add tests for the token round trip, an expired token and the extractor with valid and tampered headers, none of which need Postgres. Run the crate's tests, clippy, the formatters the justfile uses and the workspace check, document the token flow with curl in the README, and put the output in the pull request description.",
  "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 on its own branch. The diff adds jsonwebtoken and actix-web-httpauth to the root Cargo.toml and the crate's, adds src/jwt.rs with its tests, edits src/auth_handler.rs for the token handler and the two-path extractor, registers /api/token in src/main.rs, updates Cargo.lock, and extends the crate's README.md with the environment variable and the curl sequence. static/main.js keeps using the cookie flow unchanged.

The run's record keeps the cargo test -p simple-auth-server output with the new cases, the clippy and format results, and the workspace cargo check, so a reviewer sees the crate compile under the workspace's resolver and edition rather than only in isolation.

Before merging, a reviewer checks that JWT_SECRET has no default the way SECRET_KEY does, that the token lifetime matches the session's one-day TTL or is deliberately shorter, that the extractor does not accept a token when the Authorization scheme is not Bearer, and that the README's curl example uses the /api prefix.

Run it on every new service needing API clients

A team with several Actix services starts one run per repository with POST /o/{org}/sessions, this prompt with the crate path swapped in, and the repository in resources. Each run reads its own extractor and error type, so a service that already uses actix-web-httpauth gets only the token route and claims, and each opens its own pull request with its own test output.

Everyone in the org can open the run while it works, and its starter or an org admin can send a follow-up through POST /o/{org}/sessions/{id}/messages to change the lifetime or add a refresh route; the key's webhook_url posts run.completed with data.session_url when each turn ends.

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

Why run it on Rush?

Token auth added in a hurry reuses the secret that already protects something else, defaults it when the variable is missing, or accepts a token whose expiry was never checked. In a Rush sandbox the agent reads how the secret is used today, keeps the new one separate with no fallback, and runs the round-trip, expiry and tampering tests before it pushes, with the output kept in the record.

The change spans the workspace manifest, a new module, the extractor every protected handler relies on, the router and the README. One run returns all of it with its log, and the same prompt runs across every Actix service in the org at once, each in its own sandbox reading its own handlers.

Frequently asked questions

Does the cookie login stop working?

No. The extractor tries the bearer header first and falls back to the Identity cookie, so static/main.js and anyone using POST /api/auth keep working. Only clients that call POST /api/token get a JWT, and they send it in the Authorization header.

Why a separate JWT_SECRET?

SECRET_KEY already seeds the argon2 hashing in utils.rs and the cookie session key, and it falls back to a fixed string when unset. Signing tokens with it would tie three things to one value and to that default. JWT_SECRET has no fallback, so a missing variable fails at startup rather than signing with a known key.

Can the tests run without Postgres?

The new ones can. The token round trip and expiry tests touch only jwt.rs, and the extractor tests build an App with the get_me route, which needs no pool. Only the credential check behind /api/token queries users, and that is the same Diesel query login already runs.

Is there a refresh token?

Not in this run. The token carries exp and the client asks for a new one with its credentials when it expires. A refresh route with its own lifetime and revocation is a follow-up the pull request names, and a message to the same run can add it.

More Actix Web jobs

The same job on other stacks

Keep reading