# Add Refresh Tokens to a Gin JWT API

Yes. An agent adds a stored, rotating refresh token beside the 24-hour JWT a Gin API issues, a /users/refresh route that swaps it, tests and lint, and opens a PR.

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

## What the agent does

The agent reads how tokens are made and checked before adding a second kind. In an API shaped like gothinkster/golang-gin-realworld-example-app, `go.mod` declares `go 1.21` with `gin-gonic/gin` v1.10.0, `golang-jwt/jwt/v5` v5.2.1, `gorm.io/gorm` v1.25.12 on the SQLite driver, `go-playground/validator/v10` and `stretchr/testify`. `common/utils.go` holds `GenToken(id)`, which signs an HS256 token with claims `id` and an `exp` 24 hours out using the `JWTSecret` constant, plus `RandString`, which draws from `crypto/rand`. `users/middlewares.go` has `extractToken`, which accepts an `Authorization: Token` header or an `access_token` query parameter, and `AuthMiddleware(auto401)`, which parses the token, checks the signing method, and sets `my_user_id` and `my_user_model` on the context. `users/routers.go` registers `POST /users`, `POST /users/login`, `GET /user` and `PUT /user`; `UsersLogin` finds the user by email, checks the password and answers through `UserSerializer`, whose `Response()` in `users/serializers.go` calls `GenToken` for the `token` field. `users/models.go` has `UserModel` and a `FollowModel` on `gorm.Model`, and `AutoMigrate` creates both. A token lives a day and there is no way to replace it without the password.

The agent adds `RefreshTokenModel` to `users/models.go` on `gorm.Model` with `UserID`, `TokenHash`, `ExpiresAt` and `RevokedAt`, and adds it to `AutoMigrate`. In `common/utils.go` a `GenRefreshToken()` returns a long `RandString` value, and the model stores only its SHA-256 hash, so a copy of the database does not hand out sessions. `UserResponse` gains a `refresh_token` field, filled on registration and login only, so `GET /user` and `PUT /user` keep answering the shape the RealWorld spec defines plus nothing.

`POST /users/refresh` is the new handler in `users/routers.go`, registered beside `/users/login` outside `AuthMiddleware`. It binds `{"user": {"refresh_token": "…"}}` through a validator in `users/validators.go` in the file's existing style, hashes the value, loads the row, and refuses with `401` when it is missing, expired or revoked. On success it sets `RevokedAt` on the old row, inserts a new one for the same user, and answers the usual `UserResponse` with a fresh `token` from `GenToken` and the new `refresh_token`. A reuse of a revoked token revokes every live token for that user, which is the standard answer to a stolen refresh token, and the pull request explains it.

Tests go into `users/unit_test.go`, which already boots a test database in `TestMain` and drives handlers with `httptest` and `testify`: login returns both tokens, refresh returns a new pair and the old refresh token then fails, an expired row fails, and a reused token revokes the rest. Before pushing the agent runs what `.github/workflows/ci.yml` runs: `scripts/gofmt.sh`, `scripts/coverage.sh`, `golangci-lint run` with the `staticcheck`, `unused` and `misspell` linters from `.golangci.yml`, `gosec ./...`, and the Newman collection through `scripts/run-api-tests.sh` against a running server, which still passes because every existing response keeps its fields.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add refresh tokens to this Gin API and open a pull request. Read go.mod, hello.go, common/utils.go, users/models.go, users/middlewares.go, users/routers.go, users/serializers.go, users/validators.go, users/unit_test.go, .golangci.yml, scripts/gofmt.sh, scripts/coverage.sh, scripts/run-api-tests.sh and .github/workflows/ci.yml first. Add RefreshTokenModel on gorm.Model with UserID, TokenHash, ExpiresAt and RevokedAt, add it to AutoMigrate, and add GenRefreshToken in common/utils.go built on RandString; store only a SHA-256 hash. Add refresh_token to UserResponse, filled on registration and login only. Add POST /users/refresh beside /users/login, outside AuthMiddleware, that binds the token through a validator in the existing style, refuses missing, expired or revoked tokens with 401, rotates on success by revoking the old row and inserting a new one, and revokes every live token for the user when a revoked token is reused; answer with the usual UserResponse carrying a new token and refresh_token. Add tests to users/unit_test.go for login returning both tokens, rotation, the old token failing after rotation, expiry and reuse detection. Run scripts/gofmt.sh, scripts/coverage.sh, golangci-lint run, gosec ./... and scripts/run-api-tests.sh against a running server, and put the output in the pull request. Do not change GenToken's claims or AuthMiddleware.",
  "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 `users/models.go`, `users/routers.go`, `users/serializers.go`, `users/validators.go`, `users/unit_test.go` and `common/utils.go`. The description shows the coverage lines for `users` and `common`, clean `golangci-lint` and `gosec` output, the Newman summary from the API collection, and a `curl` exchange: a login answering `token` and `refresh_token`, then a refresh answering a new pair, then the old refresh token answering `401`.

On a repository with this `CI` workflow, the pull request runs the gofmt check, the coverage script on Go 1.21, 1.22 and 1.23, the linters, the security scan and the API tests against the built server. The collection checks the fields the RealWorld spec defines, which are unchanged, so it passes.

A reviewer checks the refresh token's lifetime against how long they want a session to survive without a password, that the `401` on reuse is the behaviour they want for a user whose token was copied, and that the hash is what reaches the database. Then they decide whether to shorten the access token's 24 hours in `GenToken`, which the pull request leaves as it is and mentions.

## Run it on every new Gin service with JWT auth

Send one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own token helper and middleware, so a service that already stores sessions in Redis gets its refresh tokens there rather than in a GORM table, and a service whose JWT carries more claims keeps them on the token the refresh handler issues.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn finishes, with the `session_url` to read the pull request link from, so a handler on your server can post it where that service's owners review.

## Why run it on Rush?

The dangerous part of a refresh token is the path nobody exercises by hand: the reuse of a token that was already rotated. The agent writes that case as a test, runs the whole suite with coverage, and drives the real server with `curl` and the Newman collection in its sandbox, and every command and its output stays in the run's record, so the pull request shows the `401` on reuse rather than promising it.

The repository's CI runs five jobs including a security scan and an API suite, and the agent runs the same scripts before pushing, so the pull request arrives green instead of after a round trip for a `gosec` finding on the new random source. The same request body works on every Gin service a team owns.

## Frequently asked questions

### Does the access token change?

No. `GenToken` keeps its claims and its 24-hour `exp`, and `AuthMiddleware` is untouched, so every existing client keeps working. The pull request notes that a shorter access token is the usual next step once refresh exists, and leaves that choice to the reviewer.

### Why store a hash instead of the token?

The table would otherwise be a list of valid sessions for anyone who reads the SQLite file or a backup. Storing a SHA-256 of the token means the handler can still find the row from the value a client sends, while the stored column is useless on its own.

### What happens if a refresh token is stolen?

Rotation means the thief and the real client each hold a token only one of which is live. When the stale one is presented, the handler revokes every token for that user, so both sides have to log in again. The test suite covers that path.

### Will the Postman collection still pass?

Yes. The collection checks the fields the RealWorld spec defines on each response, and the change adds `refresh_token` on login and registration without removing or renaming anything. The agent runs the collection against the built server before pushing.

## More Gin jobs

- [Add Request IDs and Structured Logging to a Gin API from a Linear Issue](https://getrush.ai/run/add-request-id-logging/gin/)
- [Add Request Timeouts to a Gin API](https://getrush.ai/run/add-request-timeouts/gin/)
- [Add Security Headers to a Gin API](https://getrush.ai/run/add-security-headers/gin/)

## The same job on other stacks

- [Add Refresh Tokens to an Express API That Uses jsonwebtoken](https://getrush.ai/run/add-refresh-tokens/jsonwebtoken/)
- [Add Refresh Token Rotation to a NextAuth.js App](https://getrush.ai/run/add-refresh-tokens/next-auth/)
- [Add Refresh Tokens to a FastAPI App on SQLModel](https://getrush.ai/run/add-refresh-tokens/sqlmodel/)

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