0
# OAuth Flows
1
2
Complete OAuth 2.0 authorization flow implementation providing fine-grained control over the authentication process. Supports both web application and installed application flows with customizable redirect handling and token management.
3
4
## Capabilities
5
6
### Base Flow Class
7
8
Core OAuth 2.0 flow implementation that works with both web and installed application patterns.
9
10
```python { .api }
11
class Flow:
12
"""OAuth 2.0 Authorization Flow for Google APIs."""
13
14
def __init__(
15
self,
16
oauth2session: requests_oauthlib.OAuth2Session,
17
client_type: str,
18
client_config: Mapping[str, Any],
19
redirect_uri: Optional[str] = None,
20
code_verifier: Optional[str] = None,
21
autogenerate_code_verifier: bool = True
22
):
23
"""
24
Initialize OAuth 2.0 flow.
25
26
Args:
27
oauth2session: OAuth 2.0 session from requests-oauthlib
28
client_type: Either "web" or "installed"
29
client_config: Client configuration in Google client secrets format
30
redirect_uri: OAuth 2.0 redirect URI (optional at creation time)
31
code_verifier: PKCE code verifier string (43-128 chars)
32
autogenerate_code_verifier: Auto-generate PKCE code verifier
33
"""
34
35
@classmethod
36
def from_client_config(
37
cls,
38
client_config: Mapping[str, Any],
39
scopes: Sequence[str],
40
**kwargs
41
) -> "Flow":
42
"""
43
Create Flow from client configuration dictionary.
44
45
Args:
46
client_config: Client configuration in Google client secrets format
47
scopes: List of OAuth 2.0 scopes to request
48
**kwargs: Additional parameters for OAuth2Session
49
50
Returns:
51
Configured Flow instance
52
53
Raises:
54
ValueError: If client configuration format is invalid
55
"""
56
57
@classmethod
58
def from_client_secrets_file(
59
cls,
60
client_secrets_file: str,
61
scopes: Sequence[str],
62
**kwargs
63
) -> "Flow":
64
"""
65
Create Flow from client secrets JSON file.
66
67
Args:
68
client_secrets_file: Path to client secrets .json file
69
scopes: List of OAuth 2.0 scopes to request
70
**kwargs: Additional parameters for OAuth2Session
71
72
Returns:
73
Configured Flow instance
74
"""
75
76
def authorization_url(self, **kwargs) -> Tuple[str, str]:
77
"""
78
Generate authorization URL for user consent.
79
80
First step in OAuth 2.0 flow. User's browser should visit returned URL.
81
82
Args:
83
**kwargs: Additional parameters for authorization URL
84
85
Returns:
86
Tuple of (authorization_url, state) where state is used for verification
87
"""
88
89
def fetch_token(self, **kwargs) -> Mapping[str, str]:
90
"""
91
Complete authorization flow and obtain access token.
92
93
Final step after user grants consent. Exchanges authorization code for tokens.
94
95
Args:
96
**kwargs: Must include either 'code' or 'authorization_response'
97
98
Returns:
99
Token dictionary with access_token, refresh_token, etc.
100
"""
101
102
@property
103
def credentials(self) -> google.oauth2.credentials.Credentials:
104
"""
105
OAuth 2.0 credentials from the session.
106
107
Returns:
108
Google Auth credentials object
109
110
Raises:
111
ValueError: If no access token available (call fetch_token first)
112
"""
113
114
@property
115
def redirect_uri(self) -> str:
116
"""OAuth 2.0 redirect URI."""
117
118
@redirect_uri.setter
119
def redirect_uri(self, value: str):
120
"""Set OAuth 2.0 redirect URI."""
121
122
def authorized_session(self) -> google.auth.transport.requests.AuthorizedSession:
123
"""
124
Returns requests session authorized with credentials.
125
126
Returns:
127
Authorized session for making API calls
128
"""
129
```
130
131
### Installed Application Flow
132
133
Specialized flow for desktop applications and command-line tools with local server redirect handling.
134
135
```python { .api }
136
class InstalledAppFlow(Flow):
137
"""Authorization flow for installed applications."""
138
139
def run_local_server(
140
self,
141
host: str = "localhost",
142
bind_addr: Optional[str] = None,
143
port: int = 8080,
144
authorization_prompt_message: Optional[str] = None,
145
success_message: str = "The authentication flow has completed.",
146
open_browser: bool = True,
147
redirect_uri_trailing_slash: bool = True,
148
timeout_seconds: Optional[int] = None,
149
token_audience: Optional[str] = None,
150
browser: Optional[str] = None,
151
**kwargs
152
) -> google.oauth2.credentials.Credentials:
153
"""
154
Run complete OAuth flow using local web server.
155
156
Starts local server, opens browser for user authorization, handles
157
redirect, exchanges code for tokens, and returns credentials.
158
159
Args:
160
host: Hostname for local redirect server
161
bind_addr: IP address to bind server (defaults to host)
162
port: Port for local redirect server
163
authorization_prompt_message: Message shown to user (None to suppress)
164
success_message: Message displayed in browser after completion
165
open_browser: Whether to automatically open browser
166
redirect_uri_trailing_slash: Include trailing slash in redirect URI
167
timeout_seconds: Server timeout (None for no timeout)
168
token_audience: Token audience for access token
169
browser: Specific browser to use (None for default)
170
**kwargs: Additional parameters for authorization_url
171
172
Returns:
173
OAuth 2.0 credentials for authenticated user
174
175
Raises:
176
Various exceptions for network, OAuth, or configuration errors
177
"""
178
```
179
180
## Usage Examples
181
182
### Basic Web Application Flow
183
184
```python
185
from google_auth_oauthlib.flow import Flow
186
187
# Load client configuration
188
client_config = {
189
"web": {
190
"client_id": "your-client-id.apps.googleusercontent.com",
191
"client_secret": "your-client-secret",
192
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
193
"token_uri": "https://oauth2.googleapis.com/token",
194
"redirect_uris": ["http://localhost:8080/callback"]
195
}
196
}
197
198
# Create flow
199
flow = Flow.from_client_config(
200
client_config,
201
scopes=['https://www.googleapis.com/auth/cloud-platform']
202
)
203
flow.redirect_uri = 'http://localhost:8080/callback'
204
205
# Step 1: Get authorization URL
206
auth_url, state = flow.authorization_url(
207
access_type='offline',
208
include_granted_scopes='true'
209
)
210
211
print(f"Visit this URL to authorize: {auth_url}")
212
213
# Step 2: After user authorization, exchange code for token
214
authorization_code = input("Enter authorization code: ")
215
flow.fetch_token(code=authorization_code)
216
217
# Get credentials
218
credentials = flow.credentials
219
```
220
221
### Installed Application Flow
222
223
```python
224
from google_auth_oauthlib.flow import InstalledAppFlow
225
226
# Create flow from client secrets file
227
flow = InstalledAppFlow.from_client_secrets_file(
228
'client_secrets.json',
229
scopes=['https://www.googleapis.com/auth/drive.readonly']
230
)
231
232
# Run complete flow with local server
233
credentials = flow.run_local_server(
234
port=8080,
235
open_browser=True
236
)
237
238
# Use credentials
239
session = flow.authorized_session()
240
response = session.get('https://www.googleapis.com/drive/v3/files')
241
```
242
243
### Custom Local Server Configuration
244
245
```python
246
# Configure local server behavior
247
credentials = flow.run_local_server(
248
host='127.0.0.1',
249
port=9090,
250
authorization_prompt_message="Please visit this URL: {url}",
251
success_message="Authorization complete! You may close this window.",
252
open_browser=False,
253
timeout_seconds=300
254
)
255
```
256
257
### PKCE (Proof Key for Code Exchange)
258
259
```python
260
# Flow automatically handles PKCE for enhanced security
261
flow = Flow.from_client_config(
262
client_config,
263
scopes=scopes,
264
code_verifier='custom-verifier-string' # Or auto-generate
265
)
266
267
# PKCE parameters automatically included in authorization URL
268
auth_url, state = flow.authorization_url()
269
```
270
271
## Flow Attributes
272
273
```python { .api }
274
# Flow instance attributes
275
flow.client_type: str # "web" or "installed"
276
flow.client_config: Mapping[str, Any] # OAuth client configuration
277
flow.oauth2session: requests_oauthlib.OAuth2Session # Underlying session
278
flow.redirect_uri: str # OAuth redirect URI
279
flow.code_verifier: Optional[str] # PKCE code verifier
280
```
281
282
## Constants
283
284
```python { .api }
285
# Default messages for InstalledAppFlow
286
InstalledAppFlow._DEFAULT_AUTH_PROMPT_MESSAGE: str
287
InstalledAppFlow._DEFAULT_AUTH_CODE_MESSAGE: str
288
InstalledAppFlow._DEFAULT_WEB_SUCCESS_MESSAGE: str
289
```