0
# Exception Handling
1
2
Comprehensive exception hierarchy for handling authentication errors, backend configuration issues, pipeline failures, and security violations. The exception system provides detailed error information and enables proper error handling throughout the social authentication process.
3
4
## Capabilities
5
6
### Base Exception Classes
7
8
Foundation exception classes that provide the structure for all social authentication error handling.
9
10
```python { .api }
11
class SocialAuthBaseException(ValueError):
12
"""
13
Base class for all social authentication exceptions.
14
15
All social auth related exceptions inherit from this base class,
16
making it easy to catch any social auth error with a single except clause.
17
"""
18
19
class AuthException(SocialAuthBaseException):
20
"""
21
General authentication process exception.
22
23
Raised when authentication fails due to provider issues, invalid responses,
24
network problems, or other general authentication errors.
25
"""
26
27
def __init__(self, backend, *args, **kwargs):
28
"""
29
Initialize authentication exception.
30
31
Parameters:
32
- backend: Authentication backend instance that raised the exception
33
- Additional arguments passed to parent exception
34
"""
35
self.backend = backend
36
super().__init__(*args, **kwargs)
37
```
38
39
### Backend Configuration Exceptions
40
41
Exceptions related to backend configuration, availability, and setup issues.
42
43
```python { .api }
44
class WrongBackend(SocialAuthBaseException):
45
"""
46
Incorrect authentication service error.
47
48
Raised when the requested backend name doesn't match the expected
49
backend for the current authentication flow.
50
"""
51
52
def __init__(self, backend_name: str):
53
"""
54
Initialize wrong backend exception.
55
56
Parameters:
57
- backend_name: Name of the incorrect backend
58
"""
59
self.backend_name = backend_name
60
super().__init__()
61
62
def __str__(self) -> str:
63
return f'Incorrect authentication service "{self.backend_name}"'
64
65
class MissingBackend(WrongBackend):
66
"""
67
Missing backend entry error.
68
69
Raised when a requested backend is not available in the current
70
configuration or has not been properly installed/configured.
71
"""
72
73
def __str__(self) -> str:
74
return f'Missing backend "{self.backend_name}" entry'
75
```
76
77
### Strategy and Feature Exceptions
78
79
Exceptions related to strategy implementation and feature support.
80
81
```python { .api }
82
class StrategyMissingFeatureError(SocialAuthBaseException):
83
"""
84
Strategy does not support required feature.
85
86
Raised when the current strategy implementation lacks support
87
for a feature required by a backend or pipeline function.
88
"""
89
90
def __init__(self, strategy_name: str, feature_name: str):
91
"""
92
Initialize missing feature exception.
93
94
Parameters:
95
- strategy_name: Name of the strategy implementation
96
- feature_name: Name of the missing feature
97
"""
98
self.strategy_name = strategy_name
99
self.feature_name = feature_name
100
super().__init__()
101
102
def __str__(self) -> str:
103
return f"Strategy {self.strategy_name} does not support {self.feature_name}"
104
```
105
106
### User Account Management Exceptions
107
108
Exceptions related to user account operations and restrictions.
109
110
```python { .api }
111
class NotAllowedToDisconnect(SocialAuthBaseException):
112
"""
113
User not allowed to disconnect social account.
114
115
Raised when a user attempts to disconnect a social account but doing so
116
would leave them without any way to authenticate (no password, no other
117
social accounts, etc.).
118
"""
119
120
def __str__(self) -> str:
121
return "This account is not allowed to be disconnected."
122
```
123
124
### Authentication Flow Exceptions
125
126
Exceptions that occur during the authentication process and user interaction.
127
128
```python { .api }
129
class AuthCanceled(AuthException):
130
"""
131
Authentication canceled by user.
132
133
Raised when the user explicitly cancels the authentication process
134
at the provider's authorization page.
135
"""
136
137
def __str__(self) -> str:
138
return "Authentication process was canceled by the user"
139
140
class AuthForbidden(AuthException):
141
"""
142
Authentication forbidden by policy.
143
144
Raised when authentication is blocked by access control policies
145
such as domain restrictions, email whitelists, or other security rules.
146
"""
147
148
def __str__(self) -> str:
149
return "Authentication is forbidden by access control policy"
150
151
class AuthFailed(AuthException):
152
"""
153
Authentication failed due to invalid credentials or provider error.
154
155
Raised when the authentication provider rejects the credentials
156
or returns an error response during the authentication process.
157
"""
158
159
def __str__(self) -> str:
160
return "Authentication failed"
161
162
class AuthMissingParameter(AuthException):
163
"""
164
Required authentication parameter missing.
165
166
Raised when a required parameter is missing from the authentication
167
request or provider response.
168
"""
169
170
def __init__(self, backend, parameter, *args, **kwargs):
171
"""
172
Initialize missing parameter exception.
173
174
Parameters:
175
- backend: Authentication backend instance
176
- parameter: Name of the missing parameter
177
"""
178
self.parameter = parameter
179
super().__init__(backend, *args, **kwargs)
180
181
def __str__(self) -> str:
182
return f"Missing required parameter: {self.parameter}"
183
184
class AuthStateMissing(AuthException):
185
"""
186
OAuth state parameter missing or invalid.
187
188
Raised when the OAuth state parameter is missing from the callback
189
or doesn't match the expected value, indicating a potential CSRF attack.
190
"""
191
192
def __str__(self) -> str:
193
return "OAuth state parameter is missing or invalid"
194
195
class AuthStateForbidden(AuthException):
196
"""
197
OAuth state parameter validation failed.
198
199
Raised when the OAuth state parameter fails validation checks,
200
indicating a security issue or tampering attempt.
201
"""
202
203
def __str__(self) -> str:
204
return "OAuth state parameter validation failed"
205
```
206
207
### Network and Communication Exceptions
208
209
Exceptions related to network connectivity and provider communication.
210
211
```python { .api }
212
class AuthConnectionError(AuthException):
213
"""
214
Connection error during authentication.
215
216
Raised when network connectivity issues prevent communication
217
with the authentication provider's servers.
218
"""
219
220
def __str__(self) -> str:
221
return "Failed to connect to authentication provider"
222
223
class AuthUnreachableProvider(AuthException):
224
"""
225
Authentication provider is unreachable.
226
227
Raised when the authentication provider's servers are unavailable
228
or returning error responses consistently.
229
"""
230
231
def __str__(self) -> str:
232
return "Authentication provider is currently unreachable"
233
234
class AuthTimeout(AuthException):
235
"""
236
Authentication request timeout.
237
238
Raised when requests to the authentication provider exceed
239
the configured timeout period.
240
"""
241
242
def __str__(self) -> str:
243
return "Authentication request timed out"
244
245
class AuthUnknownError(AuthException):
246
"""
247
Unknown authentication error.
248
249
Raised when an unexpected error occurs during authentication
250
that doesn't fit into other exception categories.
251
"""
252
253
def __str__(self) -> str:
254
return "An unknown authentication error occurred"
255
```
256
257
### Token Management Exceptions
258
259
Exceptions related to token handling and refresh operations.
260
261
```python { .api }
262
class AuthTokenError(AuthException):
263
"""
264
Token-related authentication error.
265
266
Raised when issues occur with access tokens, refresh tokens,
267
or other authentication tokens.
268
"""
269
270
def __str__(self) -> str:
271
return "Authentication token error"
272
273
class AuthTokenRevoked(AuthTokenError):
274
"""
275
Authentication token has been revoked.
276
277
Raised when an access token or refresh token has been revoked
278
by the user or provider and is no longer valid.
279
"""
280
281
def __str__(self) -> str:
282
return "Authentication token has been revoked"
283
284
class AuthTokenExpired(AuthTokenError):
285
"""
286
Authentication token has expired.
287
288
Raised when attempting to use an expired token and no refresh
289
token is available or refresh fails.
290
"""
291
292
def __str__(self) -> str:
293
return "Authentication token has expired"
294
```
295
296
## Exception Handling Patterns
297
298
### Basic Exception Handling
299
300
```python
301
from social_core.exceptions import (
302
AuthException, AuthCanceled, AuthForbidden,
303
MissingBackend, NotAllowedToDisconnect
304
)
305
306
try:
307
user = do_complete(backend, login, user=current_user)
308
except AuthCanceled:
309
# User canceled at provider
310
messages.info(request, 'Authentication was canceled')
311
return redirect('/login/')
312
except AuthForbidden:
313
# Access denied by policy
314
messages.error(request, 'Access denied by security policy')
315
return redirect('/login/')
316
except MissingBackend as e:
317
# Backend not configured
318
messages.error(request, f'Authentication service not available: {e.backend_name}')
319
return redirect('/login/')
320
except AuthException as e:
321
# General authentication error
322
messages.error(request, f'Authentication failed: {e}')
323
return redirect('/login/')
324
```
325
326
### Disconnect Exception Handling
327
328
```python
329
from social_core.exceptions import NotAllowedToDisconnect
330
331
try:
332
backend.disconnect(user, association_id)
333
except NotAllowedToDisconnect:
334
messages.error(request, 'Cannot disconnect - this is your only login method')
335
return redirect('/profile/connections/')
336
```
337
338
### Network Error Handling
339
340
```python
341
from social_core.exceptions import (
342
AuthConnectionError, AuthUnreachableProvider, AuthTimeout
343
)
344
345
try:
346
user = backend.complete()
347
except (AuthConnectionError, AuthUnreachableProvider, AuthTimeout) as e:
348
# Network/provider issues - suggest retry
349
messages.warning(request, f'Service temporarily unavailable: {e}')
350
return redirect('/login/?retry=1')
351
except AuthException as e:
352
# Other auth errors
353
messages.error(request, f'Authentication failed: {e}')
354
return redirect('/login/')
355
```
356
357
### Custom Exception Handling
358
359
```python
360
def handle_social_auth_error(exception, backend=None):
361
"""Centralized exception handler for social auth errors."""
362
363
if isinstance(exception, AuthCanceled):
364
return {
365
'message': 'Authentication was canceled by the user',
366
'level': 'info',
367
'retry': True
368
}
369
elif isinstance(exception, AuthForbidden):
370
return {
371
'message': 'Access denied by security policy',
372
'level': 'error',
373
'retry': False
374
}
375
elif isinstance(exception, MissingBackend):
376
return {
377
'message': f'Authentication service "{exception.backend_name}" not available',
378
'level': 'error',
379
'retry': False
380
}
381
elif isinstance(exception, (AuthConnectionError, AuthTimeout)):
382
return {
383
'message': 'Service temporarily unavailable, please try again',
384
'level': 'warning',
385
'retry': True
386
}
387
else:
388
return {
389
'message': 'Authentication failed',
390
'level': 'error',
391
'retry': True
392
}
393
394
# Usage in views
395
try:
396
user = do_complete(backend, login)
397
except SocialAuthBaseException as e:
398
error_info = handle_social_auth_error(e, backend)
399
messages.add_message(request, getattr(messages, error_info['level'].upper()),
400
error_info['message'])
401
```
402
403
### Logging Exception Details
404
405
```python
406
import logging
407
from social_core.exceptions import AuthException
408
409
logger = logging.getLogger('social_auth')
410
411
try:
412
user = backend.complete()
413
except AuthException as e:
414
logger.error(
415
'Authentication failed for backend %s: %s',
416
getattr(e, 'backend', {}).name if hasattr(e, 'backend') else 'unknown',
417
str(e),
418
extra={
419
'backend': getattr(e, 'backend', None),
420
'user': request.user.id if request.user.is_authenticated else None,
421
'ip': request.META.get('REMOTE_ADDR'),
422
'user_agent': request.META.get('HTTP_USER_AGENT')
423
}
424
)
425
raise
426
```
427
428
The exception handling system provides comprehensive error coverage for all aspects of social authentication, enabling applications to provide meaningful error messages to users while maintaining security and supporting debugging during development.