0
# Google Auth Library
1
2
A comprehensive Python library for authenticating to Google APIs and services. Provides server-to-server authentication mechanisms including OAuth 2.0, JWT, and service account credentials with built-in token management, automatic refresh capabilities, and secure credential storage. Designed for high reusability across Google Cloud applications, client libraries, and any Python application requiring authentication with Google services.
3
4
## Package Information
5
6
- **Package Name**: google-auth
7
- **Language**: Python
8
- **Installation**: `pip install google-auth`
9
10
## Core Imports
11
12
```python
13
import google.auth
14
from google.auth import credentials
15
from google.oauth2 import service_account
16
```
17
18
For specific credential types:
19
20
```python
21
from google.auth import default
22
from google.oauth2 import credentials as oauth2_credentials
23
from google.auth import jwt
24
from google.auth.transport import requests
25
```
26
27
## Basic Usage
28
29
```python
30
import google.auth
31
from google.auth.transport import requests
32
33
# Use Application Default Credentials
34
credentials, project = google.auth.default(
35
scopes=['https://www.googleapis.com/auth/cloud-platform']
36
)
37
38
# Create an authenticated HTTP session
39
authed_session = requests.AuthorizedSession(credentials)
40
41
# Make authenticated requests
42
response = authed_session.get('https://www.googleapis.com/compute/v1/projects')
43
```
44
45
## Architecture
46
47
The library follows a modular design with clear separation of concerns:
48
49
- **Core Credentials**: Base credential interfaces and implementations (`google.auth.credentials`)
50
- **OAuth2 Components**: OAuth2-specific flows and service accounts (`google.oauth2.*`)
51
- **Transport Layer**: HTTP transport adapters for requests, urllib3, gRPC (`google.auth.transport.*`)
52
- **Cryptographic Utilities**: Token signing and verification (`google.auth.crypt`, `google.auth.jwt`)
53
- **Platform Integration**: Compute Engine, App Engine, external account support
54
- **Async Support**: Full async implementations using aiohttp (`google.auth.aio.*`)
55
56
This design enables flexible authentication across different environments while maintaining consistent interfaces for credential management and token handling.
57
58
## Capabilities
59
60
### Application Default Credentials
61
62
Automatically detects and loads the most appropriate credentials for the current environment, following Google Cloud's standard credential discovery flow.
63
64
```python { .api }
65
def default(
66
scopes=None,
67
request=None,
68
quota_project_id=None,
69
default_scopes=None
70
):
71
"""
72
Construct credentials from Application Default Credentials.
73
74
Args:
75
scopes (Sequence[str]): The list of scopes for the credentials
76
request (google.auth.transport.Request): HTTP transport for credential refresh
77
quota_project_id (str): Project for quota and billing
78
default_scopes (Sequence[str]): Default scopes from client library
79
80
Returns:
81
Tuple[google.auth.credentials.Credentials, Optional[str]]:
82
The constructed credentials and project ID
83
"""
84
85
def load_credentials_from_file(
86
filename,
87
scopes=None,
88
default_scopes=None,
89
quota_project_id=None,
90
request=None
91
):
92
"""
93
Load Google credentials from a file.
94
95
Args:
96
filename (str): Path to credentials file
97
scopes (Sequence[str]): Scopes for the credentials
98
default_scopes (Sequence[str]): Default scopes from client library
99
quota_project_id (str): Project for quota and billing
100
request (google.auth.transport.Request): HTTP transport
101
102
Returns:
103
Tuple[google.auth.credentials.Credentials, Optional[str]]:
104
Loaded credentials and project ID
105
"""
106
107
def load_credentials_from_dict(
108
info,
109
scopes=None,
110
default_scopes=None,
111
quota_project_id=None,
112
request=None
113
):
114
"""
115
Load Google credentials from a dictionary.
116
117
Args:
118
info (Mapping[str, str]): Credential information dictionary
119
scopes (Sequence[str]): Scopes for the credentials
120
default_scopes (Sequence[str]): Default scopes from client library
121
quota_project_id (str): Project for quota and billing
122
request (google.auth.transport.Request): HTTP transport
123
124
Returns:
125
Tuple[google.auth.credentials.Credentials, Optional[str]]:
126
Loaded credentials and project ID
127
"""
128
```
129
130
[Application Default Credentials](./adc.md)
131
132
### Service Account Credentials
133
134
Server-to-server authentication using service account keys and JWT tokens, supporting both OAuth2 flows and self-signed JWTs.
135
136
```python { .api }
137
class Credentials(google.auth.credentials.Scoped):
138
"""Service account credentials for server-to-server authentication."""
139
140
def __init__(
141
self,
142
signer,
143
service_account_email,
144
token_uri,
145
scopes=None,
146
default_scopes=None,
147
subject=None,
148
project_id=None,
149
quota_project_id=None,
150
additional_claims=None,
151
always_use_jwt_access=False,
152
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
153
trust_boundary=None,
154
**kwargs
155
): ...
156
157
@classmethod
158
def from_service_account_file(
159
cls,
160
filename,
161
**kwargs
162
): ...
163
164
@classmethod
165
def from_service_account_info(
166
cls,
167
info,
168
**kwargs
169
): ...
170
```
171
172
[Service Account Credentials](./service-accounts.md)
173
174
### OAuth2 User Credentials
175
176
OAuth2 flows for user authentication including authorization code flow, refresh tokens, and user consent management.
177
178
```python { .api }
179
class Credentials(google.auth.credentials.ReadOnlyScoped):
180
"""OAuth2 credentials for user authentication."""
181
182
def __init__(
183
self,
184
token,
185
refresh_token=None,
186
id_token=None,
187
token_uri=None,
188
client_id=None,
189
client_secret=None,
190
scopes=None,
191
default_scopes=None,
192
quota_project_id=None,
193
expiry=None,
194
rapt_token=None,
195
refresh_handler=None,
196
enable_reauth_refresh=False,
197
granted_scopes=None,
198
trust_boundary=None,
199
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
200
account=None,
201
**kwargs
202
): ...
203
```
204
205
[OAuth2 User Credentials](./oauth2-users.md)
206
207
### JWT Credentials
208
209
JSON Web Token-based authentication for service-to-service communication without OAuth2 flows.
210
211
```python { .api }
212
class Credentials(
213
google.auth.credentials.Signing,
214
google.auth.credentials.CredentialsWithQuotaProject
215
):
216
"""JWT-based credentials for service authentication."""
217
218
def __init__(
219
self,
220
signer,
221
issuer,
222
subject,
223
audience,
224
additional_claims=None,
225
**kwargs
226
): ...
227
228
def encode(signer, payload, header=None, key_id=None):
229
"""
230
Encode a JWT token.
231
232
Args:
233
signer (google.auth.crypt.Signer): The signer used to sign the JWT
234
payload (Mapping[str, str]): JWT payload claims
235
header (Mapping[str, str]): Additional JWT header fields
236
key_id (str): Key ID to add to JWT header (overrides signer key_id)
237
238
Returns:
239
bytes: Encoded JWT token
240
"""
241
242
def decode(token, certs=None, verify=True, audience=None, clock_skew_in_seconds=0):
243
"""
244
Decode and verify a JWT token.
245
246
Args:
247
token (str): The encoded JWT
248
certs (Union[str, bytes, Mapping[str, Union[str, bytes]]]): Certificate used to validate JWT signature
249
verify (bool): Whether to perform signature and claim validation
250
audience (Union[str, list]): The audience claim that this JWT should contain
251
clock_skew_in_seconds (int): The number of seconds of clock skew to tolerate
252
253
Returns:
254
Mapping[str, str]: Decoded JWT payload
255
"""
256
```
257
258
[JWT Credentials](./jwt.md)
259
260
### Transport Adapters
261
262
HTTP transport implementations for making authenticated requests across different HTTP libraries.
263
264
```python { .api }
265
class Request(google.auth.transport.Request):
266
"""Requests-based HTTP transport."""
267
268
def __init__(self, session=None): ...
269
270
class AuthorizedSession(requests.Session):
271
"""Requests session with automatic credential refresh."""
272
273
def __init__(self, credentials, **kwargs): ...
274
```
275
276
[Transport Adapters](./transport.md)
277
278
### External Account Credentials
279
280
Workload identity and external identity provider integration for multi-cloud and hybrid scenarios.
281
282
```python { .api }
283
class Credentials(google.auth.credentials.Scoped):
284
"""External account credentials for workload identity."""
285
286
def __init__(
287
self,
288
audience,
289
subject_token_type,
290
token_url,
291
**kwargs
292
): ...
293
```
294
295
[External Account Credentials](./external-accounts.md)
296
297
### Cryptographic Utilities
298
299
Token signing and verification utilities supporting RSA and ECDSA algorithms.
300
301
```python { .api }
302
class RSASigner(google.auth.crypt.Signer):
303
"""RSA-based token signer."""
304
305
def __init__(self, key): ...
306
307
def sign(self, message): ...
308
309
class ES256Signer(google.auth.crypt.Signer):
310
"""ECDSA P-256 token signer."""
311
312
def __init__(self, key): ...
313
314
def sign(self, message): ...
315
```
316
317
[Cryptographic Utilities](./crypt.md)
318
319
### Async Support
320
321
Full async implementations using aiohttp for non-blocking authentication flows.
322
323
```python { .api }
324
class Request(google.auth.transport.Request):
325
"""Async HTTP transport using aiohttp."""
326
327
def __init__(self, session=None): ...
328
329
async def __call__(self, *args, **kwargs): ...
330
331
class AuthorizedSession(aiohttp.ClientSession):
332
"""Async session with automatic credential refresh."""
333
334
def __init__(self, credentials, **kwargs): ...
335
```
336
337
[Async Support](./async.md)
338
339
## Types
340
341
```python { .api }
342
class TokenState(enum.Enum):
343
"""Token freshness states."""
344
FRESH = 1
345
STALE = 2
346
INVALID = 3
347
348
class Credentials:
349
"""Base credentials interface."""
350
351
token: Optional[str]
352
expiry: Optional[datetime.datetime]
353
354
@property
355
def token_state(self) -> TokenState: ...
356
357
@property
358
def valid(self) -> bool: ...
359
360
@property
361
def expired(self) -> bool: ...
362
363
def refresh(self, request: Request) -> None: ...
364
365
class Scoped:
366
"""Interface for credentials supporting OAuth2 scopes."""
367
368
def with_scopes(self, scopes: Sequence[str]) -> 'Credentials': ...
369
370
class CredentialsWithQuotaProject:
371
"""Interface for credentials with quota project support."""
372
373
def with_quota_project(self, quota_project_id: str) -> 'Credentials': ...
374
375
Request = Callable[[str, str, Optional[bytes], Optional[Mapping[str, str]]], Any]
376
```