0
# OAuth2 User Credentials
1
2
OAuth2 flows for user authentication including authorization code flow, refresh tokens, and user consent management. Enables applications to access Google APIs on behalf of users with their explicit consent.
3
4
## Capabilities
5
6
### User Access Token Credentials
7
8
OAuth2 credentials representing an authorized user, supporting automatic token refresh and scope-based access control.
9
10
```python { .api }
11
class Credentials(
12
google.auth.credentials.ReadOnlyScoped,
13
google.auth.credentials.CredentialsWithQuotaProject
14
):
15
"""OAuth2 credentials for user authentication."""
16
17
def __init__(
18
self,
19
token,
20
refresh_token=None,
21
id_token=None,
22
token_uri=None,
23
client_id=None,
24
client_secret=None,
25
scopes=None,
26
default_scopes=None,
27
quota_project_id=None,
28
expiry=None,
29
rapt_token=None,
30
refresh_handler=None,
31
enable_reauth_refresh=False,
32
granted_scopes=None,
33
trust_boundary=None,
34
universe_domain=google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN,
35
account=None,
36
**kwargs
37
):
38
"""
39
Initialize OAuth2 user credentials.
40
41
Args:
42
token (str): The OAuth 2.0 access token
43
refresh_token (str): The optional refresh token
44
id_token (str): The OpenID Connect ID Token
45
token_uri (str): The token server endpoint URI
46
client_id (str): The OAuth 2.0 client identifier
47
client_secret (str): The OAuth 2.0 client secret
48
scopes (Sequence[str]): User-defined scopes to request
49
default_scopes (Sequence[str]): Default scopes passed by client libraries
50
quota_project_id (str): The project for quota and billing
51
expiry (datetime.datetime): The optional expiry datetime
52
rapt_token (str): The optional rapt token for reauth
53
refresh_handler (Callable): Custom refresh handler
54
enable_reauth_refresh (bool): Whether to enable reauth refresh
55
granted_scopes (Sequence[str]): The scopes that were granted
56
trust_boundary (str): String representation of trust boundary meta
57
universe_domain (str): The STS audience which contains the resource name
58
account (str): Account identifier
59
"""
60
61
def refresh(self, request):
62
"""
63
Refresh the access token using the refresh token.
64
65
Args:
66
request (google.auth.transport.Request): HTTP transport for making requests
67
68
Raises:
69
google.auth.exceptions.RefreshError: If credentials cannot be refreshed
70
"""
71
72
def with_scopes(self, scopes):
73
"""
74
Create a copy of these credentials with specified scopes.
75
76
Args:
77
scopes (Sequence[str]): The list of scopes to attach
78
79
Returns:
80
Credentials: A new credentials instance
81
"""
82
83
def with_quota_project(self, quota_project_id):
84
"""
85
Create a copy with a specified quota project ID.
86
87
Args:
88
quota_project_id (str): The project for quota and billing
89
90
Returns:
91
Credentials: A new credentials instance
92
"""
93
```
94
95
Usage example:
96
97
```python
98
from google.oauth2 import credentials
99
100
# Create credentials from OAuth2 tokens
101
creds = credentials.Credentials(
102
token='access_token_here',
103
refresh_token='refresh_token_here',
104
token_uri='https://oauth2.googleapis.com/token',
105
client_id='client_id_here',
106
client_secret='client_secret_here'
107
)
108
109
# Use with scopes
110
creds = creds.with_scopes(['https://www.googleapis.com/auth/drive'])
111
112
# Add quota project
113
creds = creds.with_quota_project('my-billing-project')
114
```
115
116
### User Access Token Credentials (Simple)
117
118
Simplified credentials using only an access token, useful for short-lived access without refresh capability.
119
120
```python { .api }
121
class UserAccessTokenCredentials(google.auth.credentials.Credentials):
122
"""Credentials using only a user access token."""
123
124
def __init__(self, token):
125
"""
126
Initialize with access token.
127
128
Args:
129
token (str): The OAuth 2.0 access token
130
"""
131
```
132
133
Usage example:
134
135
```python
136
from google.oauth2 import credentials
137
138
# Simple access token credentials (no refresh)
139
creds = credentials.UserAccessTokenCredentials(
140
token='user_access_token_here'
141
)
142
```
143
144
### ID Token Verification
145
146
Verify and decode OpenID Connect ID tokens from Google OAuth2 flows.
147
148
```python { .api }
149
def verify_oauth2_token(id_token, request, audience=None, clock_skew_in_seconds=0):
150
"""
151
Verify an ID token issued by Google's OAuth 2.0 authorization server.
152
153
Args:
154
id_token (Union[str, bytes]): The encoded token
155
request (google.auth.transport.Request): HTTP transport for making requests
156
audience (str): The expected audience of the token
157
clock_skew_in_seconds (int): Acceptable clock skew in seconds
158
159
Returns:
160
Mapping[str, Any]: The decoded token payload
161
162
Raises:
163
google.auth.exceptions.GoogleAuthError: If the token is invalid
164
"""
165
166
def verify_token(id_token, request, audience=None, clock_skew_in_seconds=0):
167
"""
168
Verify a token against Google's public certificates.
169
170
Args:
171
id_token (Union[str, bytes]): The encoded token
172
request (google.auth.transport.Request): HTTP transport for making requests
173
audience (str): The expected audience
174
clock_skew_in_seconds (int): Clock skew tolerance
175
176
Returns:
177
Mapping[str, Any]: The decoded token payload
178
"""
179
180
def fetch_id_token(request, audience, service_account_email=None):
181
"""
182
Fetch an ID token from the metadata server.
183
184
Args:
185
request (google.auth.transport.Request): HTTP transport
186
audience (str): The audience for the ID token
187
service_account_email (str): Service account to impersonate
188
189
Returns:
190
str: The ID token
191
"""
192
```
193
194
Usage example:
195
196
```python
197
from google.oauth2 import id_token
198
from google.auth.transport import requests
199
200
# Verify ID token
201
request = requests.Request()
202
try:
203
id_info = id_token.verify_oauth2_token(
204
token_string,
205
request,
206
audience='your-client-id.apps.googleusercontent.com'
207
)
208
print(f"User ID: {id_info['sub']}")
209
print(f"Email: {id_info['email']}")
210
except ValueError:
211
print("Invalid token")
212
213
# Fetch ID token from metadata server
214
id_token_string = id_token.fetch_id_token(
215
request,
216
'https://example.com/audience'
217
)
218
```
219
220
### OAuth2 Client Utilities
221
222
Low-level OAuth2 client functionality for implementing custom flows.
223
224
```python { .api }
225
def refresh_grant(
226
request,
227
token_uri,
228
refresh_token,
229
client_id,
230
client_secret,
231
scopes=None
232
):
233
"""
234
Refresh an access token using a refresh token.
235
236
Args:
237
request (google.auth.transport.Request): HTTP transport
238
token_uri (str): The OAuth 2.0 authorization server's token endpoint URI
239
refresh_token (str): The refresh token
240
client_id (str): The OAuth 2.0 client ID
241
client_secret (str): The OAuth 2.0 client secret
242
scopes (Sequence[str]): Scopes to request
243
244
Returns:
245
Tuple[str, Optional[str], Optional[datetime], Mapping[str, str]]:
246
Access token, new refresh token, expiry, additional token response data
247
"""
248
249
def id_token_jwt_grant(request, token_uri, assertion):
250
"""
251
JWT authorization grant for ID tokens.
252
253
Args:
254
request (google.auth.transport.Request): HTTP transport
255
token_uri (str): The OAuth 2.0 authorization server's token endpoint URI
256
assertion (str): The JWT assertion
257
258
Returns:
259
Tuple[str, Optional[datetime], Mapping[str, str]]:
260
Access token, expiry, additional token response data
261
"""
262
```
263
264
## OAuth2 Utils
265
266
```python { .api }
267
def generate_refresh_request(http_client):
268
"""
269
Generate a request function for token refresh.
270
271
Args:
272
http_client: HTTP client instance
273
274
Returns:
275
Callable: Function that can be used to make HTTP requests
276
"""
277
278
def clientsecrets_to_authorized_user_info(clientsecrets_info, refresh_token):
279
"""
280
Convert client secrets to authorized user info format.
281
282
Args:
283
clientsecrets_info (Mapping[str, Any]): Client secrets JSON
284
refresh_token (str): The refresh token
285
286
Returns:
287
Mapping[str, str]: Authorized user info dictionary
288
"""
289
```
290
291
## Error Handling
292
293
```python { .api }
294
class RefreshError(google.auth.exceptions.GoogleAuthError):
295
"""Raised when credentials cannot be refreshed."""
296
297
class OAuthError(google.auth.exceptions.GoogleAuthError):
298
"""Raised for OAuth-specific errors."""
299
```
300
301
Common error scenarios:
302
- Invalid or expired refresh token
303
- Network issues during token refresh
304
- Invalid client ID or client secret
305
- Insufficient scopes for requested operations
306
- Token format or signature validation failures