---
title: Get and refresh tokens in code
summary: How an agent or backend job gets an access token, keeps it, and renews it, with plain HTTP and the standard library of your language.
section: agents
order: 5
---
# Get and refresh tokens in code

How an agent or backend job gets an access token, keeps it, and renews it, with plain HTTP and the standard library of your language.

> **Planned.** Go and TypeScript helper libraries that wrap this (a cache, early renewal, DPoP key handling) are not published yet, and nothing here needs them. See [helper libraries](/docs/connect/helpers.md).

Everything here is plain OAuth (see [agent identities](/docs/agents/identities.md), [workload identity](/docs/agents/workload-identity.md) and [acting for a person](/docs/agents/acting-for-a-person.md)). Setup values: `TESSERA_ISSUER` is the realm issuer URL, for example `https://login.kurthlabs.com/realms/acme`. The token endpoint is the issuer plus `/token`; read it from `<issuer>/.well-known/openid-configuration` if you prefer.

## Pick a grant

| You have | Send to `/token` |
| --- | --- |
| A service account with a secret or a private key | `grant_type=client_credentials`, with the client's credentials and a `resource` |
| A signed identity from the platform (GitHub Actions, a Kubernetes pod, any JWT) | `grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer` and `assertion` |
| A person's token and an agent that acts for them | `grant_type=urn:ietf:params:oauth:grant-type:token-exchange`, `subject_token` and `actor_token` |
| A person at a terminal, no browser | The device flow, [below](#device-flow) |

The full request for each is on [endpoints](/docs/reference/endpoints.md#token-token); the curl for each is on the pages linked above.

## Client credentials, cached

```sh
curl -sS "$TESSERA_ISSUER/token" -u "billing-agent:$BILLING_AGENT_SECRET" \
  -d grant_type=client_credentials \
  -d resource=https://api.acme.example \
  -d scope=invoices.read
```

The answer has `access_token`, `token_type` and `expires_in`. Keep the token until shortly before it expires, then ask again. A small cache in Go:

```go
type tokenSource struct {
	mu      sync.Mutex
	token   string
	expires time.Time
}

// Token returns the cached access token, or asks Tessera for a new one
// 30 seconds before the old one expires.
func (s *tokenSource) Token(ctx context.Context) (string, error) {
	s.mu.Lock()
	defer s.mu.Unlock()
	if s.token != "" && time.Now().Before(s.expires.Add(-30*time.Second)) {
		return s.token, nil
	}
	form := url.Values{"grant_type": {"client_credentials"}, "resource": {"https://api.acme.example"}, "scope": {"invoices.read"}}
	req, _ := http.NewRequestWithContext(ctx, http.MethodPost, os.Getenv("TESSERA_ISSUER")+"/token", strings.NewReader(form.Encode()))
	req.SetBasicAuth("billing-agent", os.Getenv("BILLING_AGENT_SECRET"))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	var body struct {
		AccessToken string `json:"access_token"`
		ExpiresIn   int    `json:"expires_in"`
		Error       string `json:"error"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&body); err != nil || resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("token request failed: %s %s", resp.Status, body.Error) // never log the secret or a token
	}
	s.token, s.expires = body.AccessToken, time.Now().Add(time.Duration(body.ExpiresIn)*time.Second)
	return s.token, nil
}
```

Call `source.Token(ctx)` before each request and send `Authorization: Bearer <token>`. If the API answers `401` with `invalid_token`, drop the cached token and ask once more.

The same in TypeScript:

```ts
let cached: { token: string; expiresAt: number } | undefined;

export async function getToken(): Promise<string> {
  if (cached && Date.now() < cached.expiresAt - 30_000) return cached.token;
  const response = await fetch(`${process.env.TESSERA_ISSUER}/token`, {
    method: "POST",
    headers: {
      authorization: `Basic ${Buffer.from(`billing-agent:${process.env.BILLING_AGENT_SECRET}`).toString("base64")}`,
      "content-type": "application/x-www-form-urlencoded",
    },
    body: new URLSearchParams({ grant_type: "client_credentials", resource: "https://api.acme.example", scope: "invoices.read" }),
    redirect: "error", // never repeat the secret at another address
  });
  const body = await response.json();
  if (!response.ok) throw new Error(`token request failed: ${response.status} ${body.error}`); // never log the secret or a token
  cached = { token: body.access_token, expiresAt: Date.now() + body.expires_in * 1000 };
  return cached.token;
}
```

To sign with a private key instead of a secret, send a `private_key_jwt` assertion (`client_assertion_type` and `client_assertion`) as described under [endpoints](/docs/reference/endpoints.md#token-token), with any JWT library.

## No stored secret: a platform identity

A GitHub Actions job, a Kubernetes pod or any other workload that can get a signed token from its platform sends it as the `assertion`, with no client secret. The federation policy that allows it is set up under [workload identity](/docs/agents/workload-identity.md), which also has the complete GitHub Actions and Kubernetes steps with curl.

```sh
curl -sS "$TESSERA_ISSUER/token" \
  -d grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer \
  --data-urlencode "assertion=$IDENTITY_TOKEN" \
  -d resource=https://api.acme.example -d scope=deploy
```

Re-read the platform token from its file or endpoint on every renewal, so a rotated token is picked up without a restart.

## Acting for a person

Exchange the person's token for one that names the agent. Both tokens go in one request, and the call is made with the agent's own client credentials:

```sh
curl -sS "$TESSERA_ISSUER/token" -u "calendar-helper:$CALENDAR_HELPER_SECRET" \
  -d grant_type=urn:ietf:params:oauth:grant-type:token-exchange \
  --data-urlencode "subject_token=$USER_TOKEN" \
  -d subject_token_type=urn:ietf:params:oauth:token-type:access_token \
  --data-urlencode "actor_token=$AGENT_TOKEN" \
  -d actor_token_type=urn:ietf:params:oauth:token-type:access_token \
  -d resource=https://api.acme.example
```

`AGENT_TOKEN` is the agent's own access token, from the client credentials call above, and it must belong to the same client. See [acting for a person](/docs/agents/acting-for-a-person.md) for what the `act` claim of the issued token holds, and for the other ways to name the actor.

## Device flow

For a program that a person starts at a terminal: ask for a code, show it, and poll until the person approves.

```sh
curl -sS "$TESSERA_ISSUER/device" -d client_id=my-cli -d scope="openid profile"
# {"device_code":"Qw8...","user_code":"BCDF-GHJK","verification_uri":"https://login.kurthlabs.com/realms/acme/device-confirm","expires_in":600,"interval":5}
```

Show the person `verification_uri` and `user_code`. Meanwhile poll every `interval` seconds:

```sh
curl -sS "$TESSERA_ISSUER/token" \
  -d grant_type=urn:ietf:params:oauth:grant-type:device_code \
  -d device_code="$DEVICE_CODE" -d client_id=my-cli
```

The answer is `authorization_pending` (keep waiting), `slow_down` (wait longer), `access_denied`, `expired_token` or tokens. See [endpoints](/docs/reference/endpoints.md#device-authorization-device) for the details.

## Things to get right

- Keep secrets out of logs and error messages: no client secret, assertion, subject or actor token, DPoP proof or access token. Log the HTTP status and the OAuth `error` code. `invalid_client` means the credentials are wrong, `invalid_grant` that the assertion or subject was refused, `invalid_target` that the resource is not allowed.
- The token endpoint must be `https` (plain `http` only for localhost). Verify certificates, and do not follow a redirect from the token endpoint, so a secret is not repeated at another address.
- Do not retry in a tight loop. A failed fetch should back off: an agent with a revoked secret should stop, not poll.
- Count expiry from when your process received the response, using `expires_in`, and renew about 30 seconds early. There is no refresh token for these grants: renewing means asking again with the same credentials. A token with a lifetime of 30 seconds or less is fetched on every call.
- For DPoP-bound tokens, send a DPoP proof with the token request and with each API request: see [protect an MCP server](/docs/agents/protect-an-mcp-server.md#dpop). Keep the key for the life of the process, because a token is bound to it.

For tokens that must stop working at once, see [revocation and the kill switch](/docs/agents/revocation-and-kill-switch.md); for how often you may ask, see [quotas](/docs/agents/quotas-and-usage.md).
