New Ory Agent Security is now live! Claim your complimentary test drive. Get Started!

Skip to main content

Derive tokens

The holder of an API key can mint a short-lived JWT or macaroon, signed by Ory Talos, that carries a chosen subset of the parent key's authority. Scopes, expiration, and custom claims are sealed into the token at mint time. Verification then needs only a signature and expiry check, with no database round-trip.

Only issued or imported root API keys can be parent credentials. A derived JWT or macaroon cannot be used to derive another token, even when the successor would have fewer scopes or a shorter TTL.

Derive tokens when you want to:

  • Hand out narrow, short-lived credentials without exposing the parent key. Each derivation drops scopes, shortens the TTL, and attaches application-specific custom_claims (for example, tenant or role). Scopes never exceed the parent's, and the derived TTL is capped at the parent's remaining lifetime.
  • Verify tokens at the edge or inside your own services. Ory Talos signs JWTs with EdDSA or RS256 and publishes the public keys at GET /v2alpha1/derivedKeys/jwks.json. Any service that holds that JWKS verifies a JWT locally, without calling Ory Talos on every request, which keeps verification resilient to database outages. Macaroons are HMAC-bound and require verification by Ory Talos.
  • Pick the right algorithm for the job. Use TOKEN_ALGORITHM_JWT when third parties or your own edge verify the token using the JWKS. Use TOKEN_ALGORITHM_MACAROON when the holder must attenuate the token further offline, without calling Ory Talos, and third-party verification isn't required. Only first-party caveats are supported: third-party caveats, which require a discharge macaroon from another service, are rejected at verification. For format details, see derived JWTs and derived macaroons.
  • Exchange API keys for JWTs at the edge. A gateway or proxy accepts a long-lived API key from the caller and exchanges it for a short-lived derived JWT. Backends behind the gateway verify the JWT locally against the JWKS, so the data path stays stateless even when the caller's credential is long-lived.
  • Bound agent authority in agentic workflows. An orchestrator holds the parent API key and mints a narrow, short-lived derived token for each agent or tool call. A leaked or misbehaving agent is then bounded by the derived token's scopes and TTL, not the parent's full authority. Use macaroons when sub-agents need to attenuate further without contacting Ory Talos.

The same endpoint (POST /v2alpha1/admin/apiKeys:verify) accepts both token types and the parent API key.

caution

Derived tokens are bearer credentials. Treat them like any short-lived session token: prefer TTLs of 5–60 minutes, never log or persist them, and read stateless derived-token verification before choosing a TTL. Revoking the parent key blocks new derivations immediately, but already-issued tokens stay valid until they expire.

Example use cases​

Ingress translates opaque API keys to JWTs​

A caller sends a long-lived opaque API key to an ingress or API gateway. The gateway runs next to Talos admin access, calls POST /v2alpha1/admin/apiKeys:derive to derive a short-lived JWT with scoped claims, and forwards only the derived JWT to backend services. Backends verify the JWT statelessly against GET /v2alpha1/derivedKeys/jwks.json.

{
"credential": "$API_SECRET",
"algorithm": "TOKEN_ALGORITHM_JWT",
"ttl": "15m",
"scopes": ["read"],
"custom_claims": {
"service": "orders-api",
"tenant": "acme"
}
}

Agent orchestrator issues constrained macaroons​

An agent orchestrator holds the parent API key secret. For each agent or task, it calls POST /v2alpha1/admin/apiKeys:derive to derive a short-lived macaroon with limited scopes and concrete caveat-style custom_claims, then gives the agent only the derived macaroon. Verification uses the same Talos verify endpoint, and the token expires quickly.

{
"credential": "$API_SECRET",
"algorithm": "TOKEN_ALGORITHM_MACAROON",
"ttl": "10m",
"scopes": ["read"],
"custom_claims": {
"access": "read_only",
"environment": "staging"
}
}

First, issue a parent key for token derivation.

RESPONSE=$(talos keys issue "derive-test" \
--actor user_1 \
--scopes "read,write" \
--format json \
-e "$TALOS_URL" 2>/dev/null)

echo "$RESPONSE" | jq .

export API_SECRET=$(echo "$RESPONSE" | jq -er '.secret')

Derive a JWT​

Send the parent key's secret to the derive endpoint with TOKEN_ALGORITHM_JWT.

RESPONSE=$(talos keys derive-token "$API_SECRET" \
--algorithm jwt \
--ttl 1h \
--claims '{"role": "viewer", "tenant": "acme"}' \
--format json \
-e "$TALOS_URL" 2>/dev/null)

echo "$RESPONSE" | jq .

export JWT_TOKEN=$(echo "$RESPONSE" | jq -er '.token.token')

Request fields​

The key fields are credential (the parent API key secret), algorithm (TOKEN_ALGORITHM_JWT or TOKEN_ALGORITHM_MACAROON), optional ttl, scopes (a subset of the parent's), audiences, and custom_claims. For the complete field reference, see the DeriveToken API reference.

For HTTP API requests, ttl accepts extended formats such as 1y, 1mo, 1w, and 1d, and compounds like 1y6mo, in addition to standard Go durations. The CLI --ttl flag expects standard Go durations such as 1h or 30m.

Response​

The response contains a token object with token.token (the derived token string), token.expire_time, token.scopes, token.audiences, and token.claims. For the complete field reference, see the DeriveToken API reference.

When metadata and a custom claim share a name, metadata takes precedence in token.claims, just as it does in verification.

Restrict a token to an audience​

An audience identifies the service that may accept a token. For example, mint a token for billing-api when a worker needs to call your billing service. Your payments service expects payments-api and rejects that token, even if both services trust the same signing keys. Audiences choose where a token can be used; scopes choose what it can do.

Audience restrictions work with both derived JWTs and macaroons. Set them when deriving the token, then configure the receiving service to check its own audience on every verification request.

If your service verifies JWTs locally, configure its JWT verifier to require the service's identifier in the aud claim. See Verify JWTs locally for the full set of checks.

Choose audience names​

Choose a stable, distinct identifier for each service, such as billing-api or https://billing.example.com. These are identifiers you define; Ory Talos does not call or discover these URLs. You don't need to register them in advance. Use separate identifiers for services or environments that should not accept each other's tokens.

Matching is exact and case sensitive: billing-api and Billing-API are different audiences. URLs must also match exactly, including any trailing slash. There is no wildcard or prefix match.

Both audiences and expected_audiences accept at most 50 values, each 1 to 255 characters long. List each value once. A request that breaks these limits or repeats a value is rejected with 400 Bad Request.

Derive a token for the receiving services​

Set audiences in the derive request, or repeat --audience with the CLI. Include only the services the caller needs. The following example allows both billing-api and reporting-api, using the API_SECRET and TALOS_URL from the earlier examples.

talos keys derive-token "$API_SECRET" \
--ttl 1h \
--audience billing-api \
--audience reporting-api \
--format json \
-e "$TALOS_URL" | jq .

export AUDIENCE_TOKEN=$(talos keys derive-token "$API_SECRET" \
--ttl 1h --audience billing-api --audience reporting-api \
--format json -e "$TALOS_URL" | jq -er '.token.token')

Verify the token at the receiving service​

Configure the billing service to send expected_audiences: ["billing-api"] with every verification request. This value comes from the receiving service's trusted configuration. Never copy it from the incoming token or let the caller choose it: the service must decide which audience it accepts.

With the CLI, use --expected-audience:

talos keys verify "$AUDIENCE_TOKEN" --expected-audience billing-api -e "$TALOS_URL"

With the API, send expected_audiences. The billing service accepts this token if its signature, expiry, and other restrictions are also valid:

curl -s -X POST "$TALOS_URL/v2alpha1/admin/apiKeys:verify" \
-H "Content-Type: application/json" \
-d "{
\"credential\": \"$AUDIENCE_TOKEN\",
\"expected_audiences\": [\"billing-api\"]
}" | jq -e '.is_valid == true'

A service the token doesn't name rejects it with VERIFICATION_ERROR_AUDIENCE_MISMATCH:

curl -s -X POST "$TALOS_URL/v2alpha1/admin/apiKeys:verify" \
-H "Content-Type: application/json" \
-d "{
\"credential\": \"$AUDIENCE_TOKEN\",
\"expected_audiences\": [\"payments-api\"]
}" | jq -e '.error_code == "VERIFICATION_ERROR_AUDIENCE_MISMATCH"'

Treat is_valid: false as a rejected credential, even when the verification endpoint returns HTTP 200. Do not retry a mismatch without expected_audiences.

If a service accepts several audience identifiers, list them in expected_audiences or repeat --expected-audience. One exact match is enough; the token does not need to name every entry. For batch verification, set expected_audiences on each item in requests. With the CLI, talos keys batch-verify --expected-audience applies the same expected audiences to every credential in the batch.

API keys and tokens without an audience​

Omitting expected_audiences, or sending an empty list, accepts only credentials that name no audience. It does not disable audience validation. The audience check behaves as follows; all other verification checks still apply:

CredentialExpected audienceAudience check
Token for billing-apibilling-apiPasses
Token for billing-apipayments-apiFails
Token for billing-apiOmitted or emptyFails
Token without an audiencebilling-apiFails
Token without an audienceOmitted or emptyPasses
API key, whether issued or importedbilling-apiFails
API key, whether issued or importedOmitted or emptyPasses

API keys carry no audience. To use one with a service that requires an audience, first derive a token for that service and send the derived token. A failed audience check rejects only that request; the API key stays active. Ory Talos rejects an API key sent with expected_audiences before looking it up, so the request doesn't count as a use of the key and the result is never cached.

Adding audience checks to an existing integration is a cutover, because the check fails in both directions. Once the service sends expected_audiences, it rejects tokens derived without an audience. Until then, it rejects tokens derived with one. To keep the cutover short, derive tokens with short TTLs, and have callers derive a new token for the service's audience when the service rejects one. Tokens derived before the cutover then fail for at most one token lifetime.

Upgrade every verification server and edge proxy before you rely on audience restrictions: a server that predates the check ignores expected_audiences and answers the unrestricted question.

Holders of a macaroon that names an audience can narrow it further offline; a caveat cannot bind a token that names none. See Token format.

Verify a derived token​

The same :verify endpoint verifies derived tokens and API keys.

talos keys verify "$JWT_TOKEN" -e "$TALOS_URL"

The response includes the token's scopes, actor, and the metadata inherited from the parent key.

Derive a macaroon​

Macaroons use HMAC-based authentication. After deriving a token, its holder can append first-party caveats offline to restrict its scopes, audience, validity period, or IP allowlist. POST /v2alpha1/admin/apiKeys:verify applies these restrictions when verifying the token. See supported caveat fields for the JSON format and validation rules.

Third-party caveats and discharge macaroons are unsupported. Use first-party caveats for restrictions the verifier can evaluate directly.

talos keys derive-token "$API_SECRET" \
--algorithm macaroon \
--ttl 30m \
-e "$TALOS_URL"

JWT versus macaroon​

FeatureJWTMacaroon
VerificationSignature-based (can verify client-side with JWKS)HMAC-based (requires server verification)
SizeLarger (base64 JSON + signature)Smaller (binary format)
Client-side verificationYes, via JWKS endpoint; see local checksNo
Custom claimsYesYes (as caveats)

JWKS endpoint​

For client-side JWT verification, fetch the public keys from the JWKS endpoint at /v2alpha1/derivedKeys/jwks.json.

talos jwk get -e "$TALOS_URL"

The endpoint serves the active public signing keys plus any retired keys still inside the verification window. Each entry includes a kid field that matches the kid header on tokens signed with that key.

Client-side caching and refresh​

Cache the JWKS response on the client so verification doesn't call Ory Talos on every request. Recommended settings:

SettingRecommended valueNotes
Cache TTL5–15 minutesBounds how long a rotated-out key keeps verifying.
Refresh-on-missEnabledIf a token's kid is unknown, refetch JWKS once.
Refresh failure modeServe staleIf the refetch fails, keep the previous keys until TTL.

Most JWT libraries (jose for Node, PyJWT/PyJWKClient for Python, go-jose, and jjwt for Java) support these patterns natively: set the cache TTL and enable refresh-on-unknown-kid. Don't poll the endpoint on a fixed interval shorter than 1 minute. It adds load without shrinking the practical revocation window, which is bounded by the longest issued token TTL.

When you rotate signing keys, keep the previous key in the JWKS response (mark it retired in the server config and don't delete the JWK) for at least the longest issued token TTL plus the maximum client cache TTL. Otherwise, clients with a freshly cached JWKS that lacks the new kid reject valid tokens until their cache expires.

Verify JWTs locally​

A service that verifies derived JWTs against the JWKS instead of calling apiKeys:verify takes on the checks Ory Talos would otherwise run. A local verifier must:

  • Verify the signature and the time and issuer claims. Check the signature against the JWKS and check exp, nbf, and iss. JWT libraries do this by default once you configure the issuer.
  • Reject tokens larger than 8,192 bytes. Ory Talos never issues a larger token and rejects one at apiKeys:verify, but JWT libraries don't apply this limit on their own. Check the length before parsing.
  • Require its own identifier in aud. Reject tokens that name another recipient and tokens that carry no aud at all, so a token minted for one service can't be replayed against another. Libraries only check the audience when you configure it: set audience in jose, pass audience= to PyJWT, set jwt.Expected.AnyAudience in go-jose, or call requireAudience in jjwt.
  • Check nid against its own tenant. Reject a token whose nid is not the network ID of the tenant the service belongs to.
  • Enforce acl against the client IP. When the token carries an acl list, accept the request only from an address inside one of its CIDR blocks.

Call POST /v2alpha1/admin/apiKeys:verify to enforce the rate limit in rl in commercial deployments. Local verification does not update the shared rate-limit counter.

Revoking a parent API key does not invalidate tokens already derived from it. Both local and API verification accept those tokens until they expire, provided their other checks pass. Use short token TTLs to limit this window.

Enforcement at derive time​

If any check fails, Ory Talos returns an error instead of a token.

  • The token must fit 8,192 bytes. The complete signed token, including its signature and any macaroon prefix, can't exceed the 8,192-byte limit that apiKeys:verify accepts. A larger token returns 400 Bad Request with the error ID credential_too_large; Ory Talos never truncates it. Reduce custom claims, audiences, or scopes, or shrink the parent key's metadata, to fit the limit.
  • Parent must be KEY_STATUS_ACTIVE. Ory Talos rejects a revoked, expired, or unknown parent key.
  • Scopes must be a subset of the parent. Requesting any scope the parent doesn't have returns 403 Forbidden. Omitting scopes inherits the full parent set.
  • TTL is capped at the parent's remaining lifetime. A ttl longer than the time left until parent.expire_time returns 400 Bad Request. The configured credentials.api_keys.max_ttl also applies.
  • Inherited fields can't be overridden. Ory Talos copies the parent's sub, actor_id, key_id, metadata, visibility, CIDR allowlist, and rate limit policy and seals them into the token claims. Requests can't set them directly.
  • Reserved claim names are stripped from custom_claims. Ory Talos owns the JWT header, the standard claims, and its own short-form claims. It removes these names from any custom_claims payload before signing: jti, sub, iss, aud, iat, exp, nbf, nid, akid, pid, act, tty, oid, scp, scope, meta, vis, acl, and rl. Use any other key for application-defined claims.

What verification checks​

Derived-token verification is stateless: no database lookup, no parent-key status check, and no re-evaluation of the parent's current scopes, rate-limit policy, or visibility. Verification only checks:

  1. Signature against the JWKS (JWT) or the HMAC secret (macaroon).
  2. exp, nbf, and iat windows. Expiry is strict; nbf and iat allow the configured clock skew, so a token stamped slightly ahead of the verifying node still verifies.
  3. Issuer matches the configured current or retired issuer.
  4. Network ID in the token claims matches the request's tenant, as defense-in-depth against tokens from another tenant.
  5. CIDR allowlist sealed into the token, against the request's source IP. This enforces the parent's IP restrictions at verify time without re-reading the parent.
  6. Audience. A token that names recipients is accepted only for a request whose expected_audiences lists one of them; a token that names none is accepted only for a request that sends no expectation.
  7. Rate limit sealed into the token. The token enforces the parent's rate limit policy as it was at derive time, and its requests count against the parent key's budget: the parent and every token derived from it share one counter. A later change to the parent's policy applies only to tokens derived after the change.

A revoked parent therefore blocks new derivations immediately but doesn't invalidate already-issued tokens; they stay valid until exp. If your threat model needs faster invalidation:

  • Use short TTLs. 5–15 minutes for service-to-service, 15–60 minutes for user sessions, and 1–5 minutes for sensitive operations. Avoid TTLs longer than your operational MTTR.
  • Rotate the JWK signing keys. Tokens signed with the rotated-out key fail signature verification once you remove the old kid from the JWKS. This invalidates every derived token signed with that key, not only those from one parent.
  • Apply your own deny list at the gateway if you need per-jti revocation. Talos doesn't maintain one for derived tokens.

Next steps​