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.
On this page
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.
Everything here is plain OAuth (see agent identities, workload identity and acting for a person). 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 |
The full request for each is on endpoints; the curl for each is on the pages linked above.
Client credentials, cached
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.readThe 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:
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:
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, 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, which also has the complete GitHub Actions and Kubernetes steps with curl.
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=deployRe-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:
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.exampleAGENT_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 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.
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:
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-cliThe answer is authorization_pending (keep waiting), slow_down (wait longer), access_denied, expired_token or tokens. See endpoints 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
errorcode.invalid_clientmeans the credentials are wrong,invalid_grantthat the assertion or subject was refused,invalid_targetthat the resource is not allowed. - The token endpoint must be
https(plainhttponly 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. 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; for how often you may ask, see quotas.