Skip to content

Commit c8d366f

Browse files
feat: add caching for Token Vault connection token exchanges (#139)
* feat(token-vault): add caching for federated connection token exchanges * fix(token-vault): address review feedback on connection token caching - Return scope on every cache hit so it matches a fresh result - Include login_hint in the cache key - Skip the cache for a non-string sub and treat wrongly typed stored entries as a miss - Document the organization errors and fix the VerifiedToken usage in the examples
2 parents ec72b74 + e32b157 commit c8d366f

9 files changed

Lines changed: 585 additions & 15 deletions

File tree

‎EXAMPLES.md‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,68 @@ async with httpx.AsyncClient() as client:
125125

126126
More info: [Client Credentials Flow](https://auth0.com/docs/get-started/authentication-and-authorization-flow/client-credentials-flow)
127127

128+
## Access Token for a Connection (Token Vault)
129+
130+
`get_access_token_for_connection()` exchanges the user's Auth0 access token for a token from a federated identity provider (such as Google) via Auth0's Token Vault.
131+
132+
Three things must exist on your Auth0 tenant before this works. The Token Vault grant must be enabled on your application, which must be a confidential (resource-server) client. The connection (for example `google-oauth2`) must be configured and enabled on that application. The user must have linked their account through Auth0's Connected Accounts flow. See the [Token Vault setup guide](https://auth0.com/docs/secure/tokens/token-vault/configure-token-vault) for the application setup and the [Connected Accounts guide](https://auth0.com/docs/secure/tokens/token-vault/connected-accounts-for-token-vault) for the user-linking step.
133+
134+
### Basic call
135+
136+
```python
137+
import httpx
138+
139+
from auth0_api_python import ApiClient, ApiClientOptions
140+
141+
api_client = ApiClient(ApiClientOptions(
142+
domain="your-tenant.auth0.com",
143+
audience="https://mcp-server.example.com",
144+
client_id="<AUTH0_CLIENT_ID>",
145+
client_secret="<AUTH0_CLIENT_SECRET>",
146+
))
147+
148+
incoming_access_token = "incoming-auth0-access-token"
149+
150+
result = await api_client.get_access_token_for_connection({
151+
"connection": "google-oauth2",
152+
"access_token": incoming_access_token,
153+
})
154+
155+
async with httpx.AsyncClient() as client:
156+
response = await client.get(
157+
"https://www.googleapis.com/calendar/v3/calendars/primary/events",
158+
headers={"Authorization": f"Bearer {result['access_token']}"},
159+
)
160+
```
161+
162+
### With caching
163+
164+
Pass a `token_store` to cache the connection token. The SDK caches by `sub` (caller), `connection` and `login_hint`, skipping the exchange on repeat calls for the same user, provider and linked account. Pass `verified=` with a `VerifiedToken` built from the `verify_access_token()` claims to reuse that verification rather than running it again inside the exchange.
165+
166+
```python
167+
from auth0_api_python import ApiClient, ApiClientOptions, VerifiedToken
168+
169+
# token_store is your AbstractTokenStore implementation.
170+
# See docs/TokenStorage.md for how to build one and for encryption details.
171+
api_client = ApiClient(ApiClientOptions(
172+
domain="your-tenant.auth0.com",
173+
audience="https://mcp-server.example.com",
174+
client_id="<AUTH0_CLIENT_ID>",
175+
client_secret="<AUTH0_CLIENT_SECRET>",
176+
token_store=your_token_store,
177+
))
178+
179+
incoming_access_token = "incoming-auth0-access-token"
180+
181+
# Verify once, then pass the result to avoid a second verification inside the exchange.
182+
claims = await api_client.verify_access_token(access_token=incoming_access_token)
183+
184+
result = await api_client.get_access_token_for_connection(
185+
{"connection": "google-oauth2", "access_token": incoming_access_token},
186+
verified=VerifiedToken(access_token=incoming_access_token, claims=claims),
187+
)
188+
```
189+
128190
## Inspecting Delegation After Token Verification
129191

130192
When a downstream API or `MCP` server receives an access token that may have been issued through

‎README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,8 @@ async def main():
122122
asyncio.run(main())
123123
```
124124

125+
When a `token_store` is configured on `ApiClientOptions`, the connection token is cached by caller, connection and `login_hint`, skipping the exchange on repeat calls. Pass `verified=` with a `VerifiedToken` built from the `verify_access_token()` claims to reuse that verification rather than verifying a second time. See [Access Token for a Connection](EXAMPLES.md#access-token-for-a-connection-token-vault) for a full example and setup requirements.
126+
125127
More info https://auth0.com/docs/secure/tokens/token-vault
126128

127129
### 5. Custom Token Exchange (Early Access)

‎docs/TokenStorage.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
# Token Storage
22

3-
The SDK can cache access tokens it mints on the caller's behalf. Currently this covers tokens
4-
returned by `get_token_on_behalf_of()`. This is separate from the `CacheAdapter` described in the
5-
[Caching Guide](Caching.md), which only caches OIDC discovery metadata and JWKS keys, never a live
6-
bearer token.
3+
The SDK can cache access tokens it mints on the caller's behalf. The same store covers tokens returned by `get_token_on_behalf_of()`, M2M tokens from `get_client_credentials_token()`, and federated-connection tokens from `get_access_token_for_connection()`. This is separate from the `CacheAdapter` described in the [Caching Guide](Caching.md), which only caches OIDC discovery metadata and JWKS keys, never a live bearer token.
74

85
## Default Behavior
96

@@ -14,6 +11,10 @@ To enable caching, pass a `token_store` to `ApiClientOptions`. Once a store is c
1411
automatically builds a cache key from the incoming token and no additional argument is needed per
1512
call.
1613

14+
## Cache Key Shapes
15+
16+
The store uses a different cache key for each exchange method. OBO tokens from `get_token_on_behalf_of()` use the most detailed key, incorporating verified issuer, incoming client, exchange tenant and client, audience, organization, session, and granted scopes (see [On Behalf Of Exchange with Caching](#on-behalf-of-exchange-with-caching) for the full design). M2M tokens from `get_client_credentials_token()` are keyed on tenant, client, audience, and the requested scope set because the server is the identity and there is no user `sub`. Connection tokens from `get_access_token_for_connection()` are keyed on tenant, client, `sub` (the caller), and `connection` with no scope dimension, since the federated provider determines what scopes apply.
17+
1718
## On Behalf Of Exchange with Caching
1819

1920
The following example verifies an incoming token and exchanges for a downstream token. The result

‎src/auth0_api_python/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,12 @@
1313
ApiError,
1414
ConfigurationError,
1515
DomainsResolverError,
16+
GetAccessTokenForConnectionError,
1617
GetClientCredentialsTokenError,
1718
GetTokenByExchangeProfileError,
1819
MissingOrganizationError,
1920
OrganizationNotAllowedError,
21+
VerifyAccessTokenError,
2022
)
2123
from .token_store import (
2224
AbstractTokenStore,
@@ -42,8 +44,10 @@
4244
"DomainsResolver",
4345
"DomainsResolverContext",
4446
"DomainsResolverError",
47+
"GetAccessTokenForConnectionError",
4548
"GetClientCredentialsTokenError",
4649
"GetTokenByExchangeProfileError",
50+
"VerifyAccessTokenError",
4751
"get_current_actor",
4852
"get_delegation_chain",
4953
"InMemoryCache",

‎src/auth0_api_python/_internal/cache_keys.py‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,9 @@ def m2m_cache_key(*, tenant: str, client_id: str, audience: str, scopes: Optiona
143143
return hashlib.sha256(fields.encode()).hexdigest()
144144

145145

146-
def token_vault_cache_key(sub: str, connection: str) -> str:
147-
"""Cache key for a Token Vault exchange, scoped to caller and connection."""
148-
fields = _FIELD_SEPARATOR.join(["token_vault", sub, connection])
146+
def token_vault_cache_key(
147+
*, sub: str, connection: str, tenant: str, client_id: str, login_hint: Optional[str] = None
148+
) -> str:
149+
"""Cache key for a Token Vault exchange, scoped to tenant, client, caller, connection, and login hint."""
150+
fields = _FIELD_SEPARATOR.join(["token_vault", tenant, client_id, sub, connection, login_hint or ""])
149151
return hashlib.sha256(fields.encode()).hexdigest()
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
"""Caching for Token Vault (federated connection) exchanges: lookup and write."""
2+
3+
import logging
4+
import time
5+
from typing import Any, Optional
6+
7+
from ..token_store import AbstractTokenStore, TokenSet
8+
from .cache_keys import _normalized_scopes, token_vault_cache_key
9+
10+
logger = logging.getLogger(__name__)
11+
12+
13+
class TokenVaultCache:
14+
"""Caches Token Vault exchange results in a token store, keyed by caller and connection.
15+
16+
ApiClient builds one TokenVaultCache when a token_store is configured and delegates
17+
every cache decision to it.
18+
"""
19+
20+
def __init__(self, token_store: AbstractTokenStore) -> None:
21+
self._store = token_store
22+
23+
def cache_key(
24+
self, tenant: str, client_id: str, sub: Any, connection: str, login_hint: Optional[str] = None
25+
) -> Optional[str]:
26+
"""Return the cache key, or None when sub is not a usable string (cache skipped with a warning)."""
27+
if not isinstance(sub, str) or not sub:
28+
logger.warning("Access token has no usable sub claim, skipping Token Vault cache")
29+
return None
30+
return token_vault_cache_key(
31+
sub=sub, connection=connection, tenant=tenant, client_id=client_id, login_hint=login_hint
32+
)
33+
34+
async def lookup(self, key: str) -> Optional[dict]:
35+
"""Return a live cached token or None. Miss cases: absent, malformed, expired."""
36+
cached: Optional[TokenSet] = None
37+
try:
38+
cached = await self._store.get(key)
39+
except Exception as exc:
40+
logger.warning("Token store read failed, treating as cache miss: %s", exc)
41+
return None
42+
43+
if cached is None:
44+
return None
45+
access_token = cached.get("access_token")
46+
expires_at = cached.get("expires_at")
47+
if not isinstance(access_token, str) or not access_token or not isinstance(expires_at, int):
48+
logger.warning("Token store returned a malformed entry, treating as cache miss")
49+
return None
50+
now = int(time.time())
51+
if expires_at <= now:
52+
return None
53+
54+
return {
55+
"access_token": access_token,
56+
"expires_in": expires_at - now,
57+
"expires_at": expires_at,
58+
"scope": cached.get("granted_scopes") or "",
59+
}
60+
61+
async def write(self, key: str, result: dict) -> None:
62+
"""Store a freshly exchanged connection token. Failures are logged and swallowed."""
63+
entry: TokenSet = {
64+
"access_token": result["access_token"],
65+
"expires_at": result["expires_at"],
66+
"granted_scopes": _normalized_scopes(result.get("scope")),
67+
}
68+
try:
69+
await self._store.set(key, entry)
70+
except Exception as exc:
71+
logger.warning("Token store write failed, token still returned: %s", exc)

‎src/auth0_api_python/api_client.py‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
from ._internal.cache_keys import m2m_cache_key
1111
from ._internal.obo_cache import OboCache
12+
from ._internal.token_vault_cache import TokenVaultCache
1213
from .cache import InMemoryCache
1314
from .config import ApiClientOptions
1415
from .errors import (
@@ -169,6 +170,11 @@ def __init__(self, options: ApiClientOptions):
169170
if options.token_store is not None
170171
else None
171172
)
173+
self._token_vault_cache = (
174+
TokenVaultCache(options.token_store)
175+
if options.token_store is not None
176+
else None
177+
)
172178

173179
self._cache_ttl = options.cache_ttl_seconds
174180

@@ -725,18 +731,29 @@ async def verify_dpop_proof(
725731

726732
return claims
727733

728-
async def get_access_token_for_connection(self, options: dict[str, Any]) -> dict[str, Any]:
734+
async def get_access_token_for_connection(
735+
self,
736+
options: dict[str, Any],
737+
*,
738+
verified: Optional[VerifiedToken] = None,
739+
) -> dict[str, Any]:
729740
"""
730741
Retrieves a token for a connection.
731742
732743
Args:
733744
options: Options for retrieving an access token for a connection.
734745
Must include 'connection' and 'access_token' keys.
735746
May optionally include 'login_hint'.
747+
verified: The already-verified token, supplied by a caller that has verified it (for
748+
example an MCP server). When omitted and a token_store is configured, the
749+
token is verified here before any cache lookup.
736750
737751
Raises:
738752
GetAccessTokenForConnectionError: If there was an issue requesting the access token.
739753
ApiError: If the token exchange endpoint returns an error.
754+
VerifyAccessTokenError: If a store is configured and either verified is omitted and the token fails verification, or verified is supplied but does not match the access token being exchanged.
755+
MissingOrganizationError: If a store is configured, verified is omitted, organization_policy is "required" and the token has no org_id claim.
756+
OrganizationNotAllowedError: If a store is configured, verified is omitted and the token's org_id is not in the organization_id allowlist.
740757
741758
Returns:
742759
Dictionary containing the token response with access_token, expires_in, and scope.
@@ -745,8 +762,8 @@ async def get_access_token_for_connection(self, options: dict[str, Any]) -> dict
745762
SUBJECT_TYPE_ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token" # noqa S105
746763
REQUESTED_TOKEN_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN = "http://auth0.com/oauth/token-type/federated-connection-access-token" # noqa S105
747764
GRANT_TYPE_FEDERATED_CONNECTION_ACCESS_TOKEN = "urn:auth0:params:oauth:grant-type:token-exchange:federated-connection-access-token" # noqa S105
748-
connection = options.get("connection")
749-
access_token = options.get("access_token")
765+
connection = options.get("connection", "")
766+
access_token = options.get("access_token", "")
750767

751768
if not connection:
752769
raise MissingRequiredArgumentError("connection")
@@ -759,6 +776,29 @@ async def get_access_token_for_connection(self, options: dict[str, Any]) -> dict
759776
if not client_id or not client_secret:
760777
raise GetAccessTokenForConnectionError("You must configure the SDK with a client_id and client_secret to use get_access_token_for_connection.")
761778

779+
cache_key = None
780+
if self._token_vault_cache is not None:
781+
if verified is None:
782+
claims = await self.verify_access_token(access_token)
783+
verified = VerifiedToken(access_token=access_token, claims=claims)
784+
elif verified.access_token != access_token:
785+
# Claims must belong to the token being exchanged or a caller could read another token's entry.
786+
raise VerifyAccessTokenError(
787+
"verified token does not match the access token being exchanged"
788+
)
789+
cache_key = self._token_vault_cache.cache_key(
790+
tenant=self.options.domain or "",
791+
client_id=self.options.client_id or "",
792+
sub=verified.claims.get("sub"),
793+
connection=connection,
794+
login_hint=options.get("login_hint"),
795+
)
796+
797+
if cache_key is not None:
798+
hit = await self._token_vault_cache.lookup(cache_key)
799+
if hit is not None:
800+
return hit
801+
762802
metadata = await self._discover()
763803

764804
token_endpoint = metadata.get("token_endpoint")
@@ -817,12 +857,18 @@ async def get_access_token_for_connection(self, options: dict[str, Any]) -> dict
817857
except (TypeError, ValueError):
818858
raise ApiError("invalid_response", "expires_in is not an integer.", 502)
819859

820-
return {
860+
result = {
821861
"access_token": access_token,
862+
"expires_in": expires_in,
822863
"expires_at": int(time.time()) + expires_in,
823864
"scope": token_endpoint_response.get("scope", "")
824865
}
825866

867+
if cache_key is not None:
868+
await self._token_vault_cache.write(cache_key, result)
869+
870+
return result
871+
826872
except httpx.TimeoutException as exc:
827873
raise ApiError(
828874
"timeout_error",

0 commit comments

Comments
 (0)