OAuth2 Token Management inside Tools: Authenticating User API Requests
Learn how to securely manage, refresh, and inject user OAuth2 tokens inside Google ADK tools to authenticate third-party API calls on behalf of end users.
Published on • November 29, 2026
AI Assistant

When enterprise AI agents act on behalf of human users, they frequently need to interact with external APIs such as GitHub, Google Workspace, Salesforce, or Stripe. Hardcoding static API keys or broad service-account tokens violates the principle of least privilege and prevents proper auditing. Instead, the agent’s tools must authenticate requests using each user’s specific OAuth2 access token.
In this guide, we explore how to manage OAuth2 tokens within Google Agent Development Kit (ADK) applications, how to pass credentials securely via InvocationContext and session state, and how to automatically handle token refreshing and authentication challenges.
1. Why Tools Must Not Manage Raw Credentials Directly
A common anti-pattern is asking the language model to hold, inspect, or pass tokens as arguments to tools. This introduces serious vulnerabilities:
- Token Leakage in Context Windows: The LLM’s conversation history is logged and could be exposed via prompt injection or prompt dumps.
- Hallucinated or Stale Tokens: The model may mangle token strings or pass expired credentials.
- Impersonation Vulnerabilities: Malicious prompts could trick the model into passing one user’s token to another user’s session.
In Google ADK, tools access contextual metadata directly through the execution environment rather than relying on LLM-supplied credentials.
+-------------------------------------------------------------+
| Client / Gateway |
| (Authenticates User, Attaches OAuth Token in Request) |
+-------------------------------------------------------------+
|
v
+-------------------------------------------------------------+
| ADK Runner |
| - Initializes Session & InvocationContext |
| - Stores encrypted tokens in ctx.session.state |
+-------------------------------------------------------------+
|
v
+-------------------------------------------------------------+
| LlmAgent |
| - Prompt: "Check my unread GitHub issues" |
| - Tool Call: list_issues(repo="google/adk-python") |
| (Notice: No token parameter exposed to the LLM!) |
+-------------------------------------------------------------+
|
v
+-------------------------------------------------------------+
| Tool Function |
| - Reads OAuth token from InvocationContext |
| - Checks expiry, triggers refresh if required |
| - Executes authenticated HTTPS request |
+-------------------------------------------------------------+
2. Accessing User Credentials via InvocationContext
ADK allows tool functions to receive the execution context by inspecting function signatures. If a tool function accepts an argument typed as InvocationContext, the ADK runner injects it automatically without exposing it to the Gemini tool schema.
Here is how to set up an OAuth2 token store and access it inside a tool:
import time
from typing import Optional, Dict, Any
import httpx
from google.adk.agents import Agent
from google.adk.agents.invocation_context import InvocationContext
class OAuthTokenManager:
"""Helper to manage token lifecycle and automatic refresh."""
def __init__(self, client_id: str, client_secret: str, refresh_url: str):
self.client_id = client_id
self.client_secret = client_secret
self.refresh_url = refresh_url
async def get_valid_token(self, token_data: Dict[str, Any]) -> str:
"""Returns the access token, refreshing if expired."""
expires_at = token_data.get("expires_at", 0)
# Refresh if token expires within 60 seconds
if time.time() >= expires_at - 60:
refresh_token = token_data.get("refresh_token")
if not refresh_token:
raise PermissionError("Access token expired and no refresh token available.")
async with httpx.AsyncClient() as client:
response = await client.post(
self.refresh_url,
data={
"grant_type": "refresh_token",
"refresh_token": refresh_token,
"client_id": self.client_id,
"client_secret": self.client_secret,
},
timeout=10.0,
)
response.raise_for_status()
payload = response.json()
# Update in-memory data
token_data["access_token"] = payload["access_token"]
token_data["expires_at"] = time.time() + payload.get("expires_in", 3600)
if "refresh_token" in payload:
token_data["refresh_token"] = payload["refresh_token"]
return token_data["access_token"]
oauth_manager = OAuthTokenManager(
client_id="oauth-client-id-xyz",
client_secret="oauth-secret-abc",
refresh_url="https://oauth2.googleapis.com/token",
)
async def fetch_user_drive_files(
folder_name: str,
ctx: InvocationContext
) -> Dict[str, Any]:
"""Fetches user files from Google Drive matching the specified folder.
Args:
folder_name: The folder name or query to search for.
"""
# 1. Retrieve the user's OAuth bundle from the ADK session state
oauth_data = ctx.session.state.get("oauth_tokens", {}).get("google")
if not oauth_data:
return {
"status": "auth_required",
"message": "User has not authorized Google Drive access. Please authenticate via /auth/google.",
}
try:
token = await oauth_manager.get_valid_token(oauth_data)
# Update session state if refreshed
ctx.session.state["oauth_tokens"]["google"] = oauth_data
except PermissionError as exc:
return {"status": "auth_required", "message": str(exc)}
# 2. Make authenticated API request
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/json",
}
async with httpx.AsyncClient() as client:
resp = await client.get(
"https://www.googleapis.com/drive/v3/files",
params={"q": f"name contains '{folder_name}' and trashed = false"},
headers=headers,
timeout=15.0,
)
if resp.status_code == 401:
return {
"status": "auth_required",
"message": "The credentials were rejected by Google Drive. Re-authentication required.",
}
resp.raise_for_status()
files = resp.json().get("files", [])
return {
"status": "success",
"file_count": len(files),
"files": [{"id": f["id"], "name": f["name"]} for f in files[:10]],
}
3. Handling Auth Challenges Gracefully in the Agent Loop
When an API returns an authentication failure or when a user has not yet consented, the tool should emit a structured status indicating auth_required. The agent can then inform the user with a tailored sign-in link instead of crashing.
drive_agent = Agent(
name="drive_assistant",
model="gemini-3.8-flash",
instruction="""
You assist users in accessing their cloud documents.
Use the `fetch_user_drive_files` tool to look up files.
If the tool returns status 'auth_required', politely explain that authorization
is needed and provide the sign-in URL clearly to the user.
""",
tools=[fetch_user_drive_files],
)
Initializing the Session with User Tokens
When hosting the agent on FastAPI or Cloud Run, your HTTP route extracts the bearer token from the client’s session cookie or JWT and injects it into the ADK Session:
from fastapi import FastAPI, Depends, HTTPException, Request
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
app = FastAPI()
session_service = InMemorySessionService()
runner = Runner(agent=drive_agent, session_service=session_service)
@app.post("/api/chat")
async def chat_endpoint(request: Request, user_message: str):
user_id = request.headers.get("X-User-ID")
if not user_id:
raise HTTPException(status_code=401, detail="Missing user identifier")
session_id = f"session_{user_id}"
session = await session_service.get_or_create(session_id=session_id)
# Injected securely from backend vault or session store
user_tokens = await fetch_user_tokens_from_vault(user_id)
session.state["oauth_tokens"] = user_tokens
# Execute agent turn
response_events = []
async for event in runner.run_async(session=session, message=user_message):
response_events.append(event)
return {"response": session.state.get("agent_response", "Done.")}
4. Security Best Practices
- State Encryption at Rest: If using persistent ADK session stores (such as Cloud Spanner or Firestore), encrypt the
oauth_tokenspayload or store references rather than plain strings. - Scope Minimization: Request only the minimal scopes required by the agent’s immediate tools (e.g.,
drive.readonlyinstead of fulldrive). - Audit Logging: Log tool invocations with the user identifier and target resource ID, but mask Authorization headers in standard logging outputs.
Takeaway: Never leak OAuth tokens into LLM prompts or tool parameter schemas. Use ADK’s InvocationContext injection to read credentials straight from the session state, ensuring secure, multi-tenant execution.
Sources
- Google ADK Documentation: https://adk.dev/
- Google GenAI SDK: https://github.com/googleapis/python-genai
- OAuth 2.0 RFC 6749: https://datatracker.ietf.org/doc/html/rfc6749