0
# Authentication
1
2
Authentication framework supporting OAuth2, OpenID Connect, and Google Cloud authentication with configurable schemes and credential management.
3
4
## Capabilities
5
6
### Authentication Core Classes
7
8
Base classes for authentication credentials and configuration.
9
10
```python { .api }
11
class AuthCredential:
12
"""Authentication credential object."""
13
14
def __init__(
15
self,
16
credential_type: 'AuthCredentialTypes',
17
credential_data: dict,
18
**kwargs
19
):
20
"""
21
Initialize authentication credential.
22
23
Args:
24
credential_type (AuthCredentialTypes): Type of credential
25
credential_data (dict): Credential data
26
**kwargs: Additional credential parameters
27
"""
28
pass
29
30
def get_credential_data(self) -> dict:
31
"""
32
Get credential data.
33
34
Returns:
35
dict: Credential data
36
"""
37
pass
38
39
def is_valid(self) -> bool:
40
"""
41
Check if credential is valid.
42
43
Returns:
44
bool: True if credential is valid
45
"""
46
pass
47
48
class AuthCredentialTypes:
49
"""Types of authentication credentials."""
50
51
OAUTH2 = "oauth2"
52
API_KEY = "api_key"
53
SERVICE_ACCOUNT = "service_account"
54
OPENID_CONNECT = "openid_connect"
55
BASIC_AUTH = "basic_auth"
56
57
class AuthConfig:
58
"""Authentication configuration."""
59
60
def __init__(
61
self,
62
auth_schemes: list = None,
63
default_scheme: str = None,
64
**kwargs
65
):
66
"""
67
Initialize authentication configuration.
68
69
Args:
70
auth_schemes (list, optional): List of authentication schemes
71
default_scheme (str, optional): Default authentication scheme
72
**kwargs: Additional configuration parameters
73
"""
74
pass
75
76
def add_scheme(self, scheme: 'AuthScheme'):
77
"""
78
Add authentication scheme.
79
80
Args:
81
scheme (AuthScheme): Authentication scheme to add
82
"""
83
pass
84
85
def get_scheme(self, scheme_name: str) -> 'AuthScheme':
86
"""
87
Get authentication scheme by name.
88
89
Args:
90
scheme_name (str): Scheme name
91
92
Returns:
93
AuthScheme: Authentication scheme
94
"""
95
pass
96
```
97
98
### Authentication Handlers
99
100
Classes for handling different authentication methods.
101
102
```python { .api }
103
class AuthHandler:
104
"""Authentication handler."""
105
106
def __init__(self, auth_config: AuthConfig, **kwargs):
107
"""
108
Initialize authentication handler.
109
110
Args:
111
auth_config (AuthConfig): Authentication configuration
112
**kwargs: Additional handler parameters
113
"""
114
pass
115
116
def authenticate(self, credential: AuthCredential) -> dict:
117
"""
118
Authenticate using provided credential.
119
120
Args:
121
credential (AuthCredential): Authentication credential
122
123
Returns:
124
dict: Authentication result with tokens/headers
125
"""
126
pass
127
128
def refresh_token(self, credential: AuthCredential) -> AuthCredential:
129
"""
130
Refresh authentication token.
131
132
Args:
133
credential (AuthCredential): Credential with refresh token
134
135
Returns:
136
AuthCredential: Updated credential with new token
137
"""
138
pass
139
140
def validate_credential(self, credential: AuthCredential) -> bool:
141
"""
142
Validate authentication credential.
143
144
Args:
145
credential (AuthCredential): Credential to validate
146
147
Returns:
148
bool: True if credential is valid
149
"""
150
pass
151
152
class OAuth2Auth(AuthHandler):
153
"""OAuth2 authentication."""
154
155
def __init__(
156
self,
157
client_id: str,
158
client_secret: str,
159
auth_url: str,
160
token_url: str,
161
scopes: list = None,
162
**kwargs
163
):
164
"""
165
Initialize OAuth2 authentication.
166
167
Args:
168
client_id (str): OAuth2 client ID
169
client_secret (str): OAuth2 client secret
170
auth_url (str): Authorization URL
171
token_url (str): Token URL
172
scopes (list, optional): OAuth2 scopes
173
**kwargs: Additional OAuth2 parameters
174
"""
175
pass
176
177
def get_authorization_url(self, redirect_uri: str, state: str = None) -> str:
178
"""
179
Get OAuth2 authorization URL.
180
181
Args:
182
redirect_uri (str): Redirect URI after authorization
183
state (str, optional): State parameter for security
184
185
Returns:
186
str: Authorization URL
187
"""
188
pass
189
190
def exchange_code_for_token(self, code: str, redirect_uri: str) -> AuthCredential:
191
"""
192
Exchange authorization code for access token.
193
194
Args:
195
code (str): Authorization code
196
redirect_uri (str): Redirect URI used in authorization
197
198
Returns:
199
AuthCredential: Credential with access token
200
"""
201
pass
202
203
class OpenIdConnectWithConfig:
204
"""OpenID Connect authentication."""
205
206
def __init__(
207
self,
208
issuer_url: str,
209
client_id: str,
210
client_secret: str = None,
211
**kwargs
212
):
213
"""
214
Initialize OpenID Connect authentication.
215
216
Args:
217
issuer_url (str): OIDC issuer URL
218
client_id (str): OIDC client ID
219
client_secret (str, optional): OIDC client secret
220
**kwargs: Additional OIDC parameters
221
"""
222
pass
223
224
def get_user_info(self, access_token: str) -> dict:
225
"""
226
Get user information from OIDC provider.
227
228
Args:
229
access_token (str): Access token
230
231
Returns:
232
dict: User information
233
"""
234
pass
235
236
def validate_id_token(self, id_token: str) -> dict:
237
"""
238
Validate and decode ID token.
239
240
Args:
241
id_token (str): ID token to validate
242
243
Returns:
244
dict: Decoded token claims
245
"""
246
pass
247
```
248
249
### Authentication Schemes
250
251
Classes for defining authentication schemes and types.
252
253
```python { .api }
254
class AuthScheme:
255
"""Authentication scheme definition."""
256
257
def __init__(
258
self,
259
name: str,
260
scheme_type: 'AuthSchemeType',
261
config: dict,
262
**kwargs
263
):
264
"""
265
Initialize authentication scheme.
266
267
Args:
268
name (str): Scheme name
269
scheme_type (AuthSchemeType): Type of authentication scheme
270
config (dict): Scheme configuration
271
**kwargs: Additional scheme parameters
272
"""
273
pass
274
275
def get_config(self) -> dict:
276
"""
277
Get scheme configuration.
278
279
Returns:
280
dict: Scheme configuration
281
"""
282
pass
283
284
def create_credential(self, credential_data: dict) -> AuthCredential:
285
"""
286
Create credential for this scheme.
287
288
Args:
289
credential_data (dict): Credential data
290
291
Returns:
292
AuthCredential: Created credential
293
"""
294
pass
295
296
class AuthSchemeType:
297
"""Types of authentication schemes."""
298
299
OAUTH2 = "oauth2"
300
OPENID_CONNECT = "openid_connect"
301
API_KEY = "api_key"
302
SERVICE_ACCOUNT = "service_account"
303
BASIC_AUTH = "basic_auth"
304
BEARER_TOKEN = "bearer_token"
305
```
306
307
## Usage Examples
308
309
### OAuth2 Authentication
310
311
```python
312
from google.adk.auth import OAuth2Auth, AuthCredential, AuthCredentialTypes
313
314
# Configure OAuth2
315
oauth2_auth = OAuth2Auth(
316
client_id="your-client-id",
317
client_secret="your-client-secret",
318
auth_url="https://accounts.google.com/o/oauth2/auth",
319
token_url="https://oauth2.googleapis.com/token",
320
scopes=["https://www.googleapis.com/auth/gmail.readonly"]
321
)
322
323
# Get authorization URL
324
auth_url = oauth2_auth.get_authorization_url(
325
redirect_uri="http://localhost:8080/callback",
326
state="random-state-string"
327
)
328
print(f"Visit: {auth_url}")
329
330
# After user authorization, exchange code for token
331
credential = oauth2_auth.exchange_code_for_token(
332
code="authorization-code-from-callback",
333
redirect_uri="http://localhost:8080/callback"
334
)
335
336
# Use credential with agents
337
from google.adk.agents import Agent
338
agent = Agent(
339
name="gmail_agent",
340
model="gemini-2.0-flash",
341
auth_credential=credential
342
)
343
```
344
345
### Service Account Authentication
346
347
```python
348
from google.adk.auth import AuthCredential, AuthCredentialTypes
349
350
# Load service account credentials
351
with open("service-account.json", "r") as f:
352
service_account_data = json.load(f)
353
354
# Create service account credential
355
credential = AuthCredential(
356
credential_type=AuthCredentialTypes.SERVICE_ACCOUNT,
357
credential_data=service_account_data
358
)
359
360
# Use with Google Cloud services
361
from google.adk.tools.bigquery import BigQueryToolset
362
bq_toolset = BigQueryToolset(
363
project_id="my-project",
364
auth_credential=credential
365
)
366
```
367
368
### API Key Authentication
369
370
```python
371
from google.adk.auth import AuthCredential, AuthCredentialTypes
372
373
# Create API key credential
374
api_key_credential = AuthCredential(
375
credential_type=AuthCredentialTypes.API_KEY,
376
credential_data={
377
"api_key": "your-api-key",
378
"header_name": "X-API-Key" # or "Authorization"
379
}
380
)
381
382
# Use with tools that require API keys
383
from google.adk.tools import RestApiTool
384
api_tool = RestApiTool(
385
base_url="https://api.example.com",
386
auth_credential=api_key_credential
387
)
388
```
389
390
### OpenID Connect Authentication
391
392
```python
393
from google.adk.auth import OpenIdConnectWithConfig, AuthCredential
394
395
# Configure OIDC
396
oidc_auth = OpenIdConnectWithConfig(
397
issuer_url="https://accounts.google.com",
398
client_id="your-client-id",
399
client_secret="your-client-secret"
400
)
401
402
# Validate ID token
403
user_info = oidc_auth.validate_id_token("jwt-id-token")
404
print(f"User: {user_info['email']}")
405
406
# Get additional user info
407
user_profile = oidc_auth.get_user_info("access-token")
408
```
409
410
### Authentication Configuration
411
412
```python
413
from google.adk.auth import AuthConfig, AuthScheme, AuthSchemeType
414
415
# Create authentication schemes
416
oauth2_scheme = AuthScheme(
417
name="google_oauth2",
418
scheme_type=AuthSchemeType.OAUTH2,
419
config={
420
"client_id": "your-client-id",
421
"client_secret": "your-client-secret",
422
"auth_url": "https://accounts.google.com/o/oauth2/auth",
423
"token_url": "https://oauth2.googleapis.com/token"
424
}
425
)
426
427
api_key_scheme = AuthScheme(
428
name="api_key_auth",
429
scheme_type=AuthSchemeType.API_KEY,
430
config={
431
"header_name": "X-API-Key"
432
}
433
)
434
435
# Configure authentication
436
auth_config = AuthConfig(
437
auth_schemes=[oauth2_scheme, api_key_scheme],
438
default_scheme="google_oauth2"
439
)
440
441
# Use with authentication handler
442
from google.adk.auth import AuthHandler
443
auth_handler = AuthHandler(auth_config)
444
```
445
446
### Multi-Service Authentication
447
448
```python
449
from google.adk.auth import AuthConfig, OAuth2Auth, AuthCredential
450
from google.adk.agents import Agent
451
452
# Configure different auth methods for different services
453
google_oauth = OAuth2Auth(
454
client_id="google-client-id",
455
client_secret="google-client-secret",
456
auth_url="https://accounts.google.com/o/oauth2/auth",
457
token_url="https://oauth2.googleapis.com/token"
458
)
459
460
# Create credentials for different services
461
gmail_credential = google_oauth.exchange_code_for_token("gmail-auth-code", "redirect-uri")
462
sheets_credential = google_oauth.exchange_code_for_token("sheets-auth-code", "redirect-uri")
463
464
# Create agent with multiple credentials
465
multi_service_agent = Agent(
466
name="office_assistant",
467
model="gemini-2.0-flash",
468
auth_credentials={
469
"gmail": gmail_credential,
470
"sheets": sheets_credential
471
}
472
)
473
```
474
475
### Token Refresh
476
477
```python
478
from google.adk.auth import OAuth2Auth, AuthHandler
479
480
oauth2_auth = OAuth2Auth(
481
client_id="client-id",
482
client_secret="client-secret",
483
auth_url="auth-url",
484
token_url="token-url"
485
)
486
487
auth_handler = AuthHandler(auth_config)
488
489
# Check if token needs refresh
490
if not auth_handler.validate_credential(existing_credential):
491
# Refresh the token
492
refreshed_credential = auth_handler.refresh_token(existing_credential)
493
494
# Update agent with new credential
495
agent.update_auth_credential(refreshed_credential)
496
```
497
498
### Custom Authentication Scheme
499
500
```python
501
from google.adk.auth import AuthScheme, AuthSchemeType, AuthCredential
502
503
# Define custom authentication scheme
504
custom_scheme = AuthScheme(
505
name="custom_auth",
506
scheme_type=AuthSchemeType.BEARER_TOKEN,
507
config={
508
"token_endpoint": "https://auth.example.com/token",
509
"username_field": "username",
510
"password_field": "password"
511
}
512
)
513
514
# Create credential for custom scheme
515
custom_credential = custom_scheme.create_credential({
516
"username": "user@example.com",
517
"password": "secure-password"
518
})
519
520
# Use with tools
521
from google.adk.tools import RestApiTool
522
custom_api_tool = RestApiTool(
523
base_url="https://api.example.com",
524
auth_credential=custom_credential
525
)
526
```