0
# Helper Utilities
1
2
Low-level integration utilities for working with requests-oauthlib sessions and converting between different credential formats. These functions provide the foundation for higher-level OAuth flows.
3
4
## Capabilities
5
6
### Session Creation
7
8
Create OAuth 2.0 sessions from Google client configuration formats.
9
10
```python { .api }
11
def session_from_client_config(
12
client_config: Mapping[str, Any],
13
scopes: Sequence[str],
14
**kwargs
15
) -> Tuple[requests_oauthlib.OAuth2Session, Mapping[str, Any]]:
16
"""
17
Create OAuth2Session from client configuration dictionary.
18
19
Args:
20
client_config: Client configuration in Google client secrets format
21
scopes: List of OAuth 2.0 scopes to request
22
**kwargs: Additional parameters passed to OAuth2Session
23
24
Returns:
25
Tuple of (OAuth2Session instance, validated client config)
26
27
Raises:
28
ValueError: If client configuration is not in correct format
29
"""
30
31
def session_from_client_secrets_file(
32
client_secrets_file: str,
33
scopes: Sequence[str],
34
**kwargs
35
) -> Tuple[requests_oauthlib.OAuth2Session, Mapping[str, Any]]:
36
"""
37
Create OAuth2Session from client secrets JSON file.
38
39
Args:
40
client_secrets_file: Path to client secrets .json file
41
scopes: List of OAuth 2.0 scopes to request
42
**kwargs: Additional parameters passed to OAuth2Session
43
44
Returns:
45
Tuple of (OAuth2Session instance, validated client config)
46
"""
47
```
48
49
### Credential Conversion
50
51
Convert between requests-oauthlib sessions and google-auth credentials objects.
52
53
```python { .api }
54
def credentials_from_session(
55
session: requests_oauthlib.OAuth2Session,
56
client_config: Optional[Mapping[str, Any]] = None
57
) -> google.oauth2.credentials.Credentials:
58
"""
59
Create Google Auth credentials from OAuth2Session.
60
61
Must call fetch_token() on session before using this function.
62
Converts session tokens to google.oauth2.credentials.Credentials format
63
for use with Google API client libraries.
64
65
Args:
66
session: OAuth2Session with valid tokens
67
client_config: Client configuration subset (e.g., client_config['web'])
68
69
Returns:
70
Google Auth credentials object with tokens and configuration
71
72
Raises:
73
ValueError: If session has no access token (call fetch_token first)
74
"""
75
```
76
77
## Usage Examples
78
79
### Creating Sessions from Configuration
80
81
```python
82
from google_auth_oauthlib.helpers import session_from_client_config
83
84
# Client configuration dictionary
85
client_config = {
86
"installed": {
87
"client_id": "your-client-id.apps.googleusercontent.com",
88
"client_secret": "your-client-secret",
89
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
90
"token_uri": "https://oauth2.googleapis.com/token"
91
}
92
}
93
94
# Create session
95
session, config = session_from_client_config(
96
client_config,
97
scopes=['https://www.googleapis.com/auth/cloud-platform']
98
)
99
100
# Use session for OAuth flow
101
auth_url, state = session.authorization_url(
102
config['auth_uri'],
103
access_type='offline'
104
)
105
```
106
107
### Loading from Client Secrets File
108
109
```python
110
from google_auth_oauthlib.helpers import session_from_client_secrets_file
111
112
# Load from file and create session
113
session, config = session_from_client_secrets_file(
114
'path/to/client_secrets.json',
115
scopes=['https://www.googleapis.com/auth/drive']
116
)
117
118
# Session is ready for OAuth flow
119
```
120
121
### Converting Session to Credentials
122
123
```python
124
from google_auth_oauthlib.helpers import credentials_from_session
125
import requests_oauthlib
126
127
# After completing OAuth flow with session
128
session = requests_oauthlib.OAuth2Session(client_id='...', scope=['...'])
129
# ... perform authorization flow ...
130
tokens = session.fetch_token('https://oauth2.googleapis.com/token', ...)
131
132
# Convert to Google Auth credentials
133
credentials = credentials_from_session(session, client_config)
134
135
# Use with Google API clients
136
from google.cloud import storage
137
storage_client = storage.Client(credentials=credentials)
138
```
139
140
### Complete Low-Level Flow Example
141
142
```python
143
from google_auth_oauthlib.helpers import (
144
session_from_client_secrets_file,
145
credentials_from_session
146
)
147
148
# Step 1: Create session from client secrets
149
session, client_config = session_from_client_secrets_file(
150
'client_secrets.json',
151
scopes=['https://www.googleapis.com/auth/bigquery']
152
)
153
154
# Step 2: Generate authorization URL
155
auth_url, state = session.authorization_url(
156
client_config['installed']['auth_uri'],
157
access_type='offline'
158
)
159
160
print(f"Visit: {auth_url}")
161
auth_code = input("Enter authorization code: ")
162
163
# Step 3: Exchange code for tokens
164
session.fetch_token(
165
client_config['installed']['token_uri'],
166
code=auth_code,
167
client_secret=client_config['installed']['client_secret']
168
)
169
170
# Step 4: Convert to Google credentials
171
credentials = credentials_from_session(session, client_config['installed'])
172
173
# Step 5: Use credentials
174
from google.cloud import bigquery
175
bigquery_client = bigquery.Client(credentials=credentials)
176
```
177
178
## Configuration Validation
179
180
```python { .api }
181
# Required configuration keys for client secrets
182
_REQUIRED_CONFIG_KEYS: frozenset = frozenset((
183
"auth_uri",
184
"token_uri",
185
"client_id"
186
))
187
```
188
189
The helpers validate that client configurations contain all required keys and raise `ValueError` if any are missing.
190
191
## Client Configuration Format
192
193
Expected client secrets format:
194
195
```json
196
{
197
"installed": {
198
"client_id": "your-client-id.apps.googleusercontent.com",
199
"client_secret": "your-client-secret",
200
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
201
"token_uri": "https://oauth2.googleapis.com/token"
202
}
203
}
204
```
205
206
Or for web applications:
207
208
```json
209
{
210
"web": {
211
"client_id": "your-client-id.apps.googleusercontent.com",
212
"client_secret": "your-client-secret",
213
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
214
"token_uri": "https://oauth2.googleapis.com/token",
215
"redirect_uris": ["http://localhost:8080/callback"]
216
}
217
}
218
```
219
220
## Error Handling
221
222
```python
223
from google_auth_oauthlib.helpers import session_from_client_config
224
225
try:
226
session, config = session_from_client_config(client_config, scopes)
227
except ValueError as e:
228
print(f"Invalid client configuration: {e}")
229
# Either missing required keys or wrong format (not 'web' or 'installed')
230
```