# Practical and Useful Patterns with ADK
๐ API Keys, Bearer Tokens, OAuth2, OpenID Connect, Service Accounts โ ADK's Authentication seamlessly integrates any auth scheme into your tools.
๐ Title: Authentication โ Tool Auth Integration
๐ URL:
๐งฉ Overview
ADK's Authentication consists of two components: AuthScheme and AuthCredential. It supports APIKey, HTTP Bearer, OAuth2, OpenID Connect, and SERVICE_ACCOUNT authentication methods, providing unified auth management across tools. OAuth2 supports browser flows, and `tool_context.state` enables token caching and expiry handling.
๐ Usage
Configuration examples for each authentication method.
Import `AuthScheme`, `AuthCredential`, `APIKeyAuth`, `HTTPBearerAuth`, and `OAuth2Auth` from `google.adk.auth`. For API Key authentication, create `APIKeyAuth(header_name="X-API-Key")` as the scheme and `AuthCredential(api_key="sk-your-api-key")` as the credential. For HTTP Bearer authentication, use `HTTPBearerAuth()` with `AuthCredential(token="your-bearer-token")`. For OAuth2 (browser flow), define the scheme with `OAuth2Auth(authorization_url="", token_url="", scopes=["read", "write"])` and provide `AuthCredential(client_id="your-client-id", client_secret="your-client-secret")`.
Using authentication in tools:
For using authentication in tools, define `call_protected_api(endpoint: str, tool_context: ToolContext)`. Retrieve cached tokens via `tool_context.state.get("user:api_token")` and reuse them if not expired. When expired, call `refresh_token(tool_context)` for a new token and store it back in `tool_context.state["user:api_token"]` for caching. Use the token in an `Authorization: Bearer` header when making API requests.
๐ Practical Patterns
**Token Caching Strategy**: Use the `user:` prefix in `tool_context.state` to cache tokens within a user's session, avoiding redundant token fetches. Always implement expiry management.
For token caching, define `get_or_refresh_token(tool_context: ToolContext) -> str`. Retrieve token data from `tool_context.state.get("user:oauth_token")` and check the `expires_at` field with a 60-second buffer. If the token is still valid, return the `access_token` directly. Otherwise, call `oauth_client.refresh(refresh_token=...)` to obtain a new token and store it in `tool_context.state["user:oauth_token"]` as a dictionary containing `access_token`, `refresh_token`, and `expires_at`.
**Service Account Authentication**: For GCP service-to-service communication, SERVICE_ACCOUNT auth enables secure API calls without user intervention.
**Multi-Layer Auth**: When using different auth methods within the same agent, configure auth per tool. Combining with OpenAPIToolset's `auth_scheme`/`auth_credential` is particularly effective.
๐ก Use Cases
๐ Third-party API authentication with API keys
๐ User-delegated API operations via OAuth2
๐๏ธ GCP inter-service communication with service accounts
๐ Token caching and automatic refresh
โ ๏ธ Caveats
- Never hardcode credentials (API keys, secrets). Retrieve from environment variables or Secret Manager.
- OAuth2 browser flows don't work in server-side batch processing. Consider service accounts or client credentials flow instead.
- Neglecting token expiry management leads to 401 errors from expired tokens. Implement automatic refresh with a time buffer.
โจ With properly configured ADK authentication, you can seamlessly embed secure API integration into your tools. Authentication is the foundation of agent trustworthiness!
#
ADK# #
AIAgent#