0
# Error Handling
1
2
Comprehensive exception hierarchy for OAuth 1.0, OAuth 2.0, and OpenID Connect errors. Provides specific error types for different failure scenarios with proper HTTP status codes and error responses.
3
4
## Capabilities
5
6
### OAuth 2.0 Base Exception
7
8
Base exception class for all OAuth 2.0 errors with standardized error response formatting.
9
10
```python { .api }
11
class OAuth2Error(Exception):
12
"""Base OAuth 2.0 exception."""
13
error: str | None
14
status_code: int
15
description: str
16
uri: str | None
17
state: str | None
18
redirect_uri: str | None
19
client_id: str | None
20
scopes: list[str]
21
response_type: str | None
22
response_mode: str | None
23
grant_type: str | None
24
25
def __init__(
26
self,
27
description: str | None = None,
28
uri: str | None = None,
29
state: str | None = None,
30
status_code: int | None = None,
31
request=None,
32
) -> None: ...
33
34
def in_uri(self, uri: str) -> str:
35
"""Format error for URI fragment or query."""
36
37
@property
38
def twotuples(self) -> list[tuple[str, str]]:
39
"""Error as list of key-value tuples."""
40
41
@property
42
def urlencoded(self) -> str:
43
"""Error as URL-encoded string."""
44
45
@property
46
def json(self) -> str:
47
"""Error as JSON string."""
48
49
@property
50
def headers(self) -> dict[str, str]:
51
"""HTTP headers for error response."""
52
```
53
54
### Client Errors
55
56
Errors related to client configuration and authentication.
57
58
```python { .api }
59
class InvalidClientError(OAuth2Error):
60
"""Invalid client credentials."""
61
error: str = "invalid_client"
62
63
class InvalidClientIdError(OAuth2Error):
64
"""Invalid client identifier."""
65
error: str = "invalid_client"
66
67
class MissingClientIdError(OAuth2Error):
68
"""Client identifier is missing."""
69
error: str = "invalid_request"
70
71
class UnauthorizedClientError(OAuth2Error):
72
"""Client not authorized for this grant type."""
73
error: str = "unauthorized_client"
74
```
75
76
### Request Errors
77
78
Errors in request format and parameters.
79
80
```python { .api }
81
class InvalidRequestError(OAuth2Error):
82
"""Invalid request format or parameters."""
83
error: str = "invalid_request"
84
85
class MissingResponseTypeError(OAuth2Error):
86
"""Missing response_type parameter."""
87
error: str = "invalid_request"
88
89
class UnsupportedResponseTypeError(OAuth2Error):
90
"""Unsupported response_type."""
91
error: str = "unsupported_response_type"
92
93
class MissingCodeError(OAuth2Error):
94
"""Missing authorization code."""
95
error: str = "invalid_request"
96
97
class InvalidGrantError(OAuth2Error):
98
"""Invalid authorization grant."""
99
error: str = "invalid_grant"
100
101
class UnsupportedGrantTypeError(OAuth2Error):
102
"""Unsupported grant_type."""
103
error: str = "unsupported_grant_type"
104
```
105
106
### Authorization Errors
107
108
Errors during authorization flow.
109
110
```python { .api }
111
class AccessDeniedError(OAuth2Error):
112
"""Authorization denied by user."""
113
error: str = "access_denied"
114
115
class InvalidRedirectURIError(OAuth2Error):
116
"""Invalid redirect URI."""
117
error: str = "invalid_request"
118
119
class MismatchingRedirectURIError(OAuth2Error):
120
"""Redirect URI doesn't match registered URI."""
121
error: str = "invalid_grant"
122
123
class MismatchingStateError(OAuth2Error):
124
"""State parameter mismatch."""
125
error: str = "invalid_request"
126
```
127
128
### Scope Errors
129
130
Errors related to scope validation and authorization.
131
132
```python { .api }
133
class InvalidScopeError(OAuth2Error):
134
"""Invalid scope parameter."""
135
error: str = "invalid_scope"
136
137
class InsufficientScopeError(OAuth2Error):
138
"""Insufficient scope for resource access."""
139
error: str = "insufficient_scope"
140
```
141
142
### Token Errors
143
144
Errors related to token validation and management.
145
146
```python { .api }
147
class InvalidTokenError(OAuth2Error):
148
"""Invalid access token."""
149
error: str = "invalid_token"
150
151
class TokenExpiredError(OAuth2Error):
152
"""Access token expired."""
153
error: str = "invalid_token"
154
155
class MissingTokenError(OAuth2Error):
156
"""Missing access token."""
157
error: str = "invalid_request"
158
159
class UnsupportedTokenTypeError(OAuth2Error):
160
"""Unsupported token type."""
161
error: str = "unsupported_token_type"
162
```
163
164
### Server Errors
165
166
Server-side errors and service availability issues.
167
168
```python { .api }
169
class ServerError(OAuth2Error):
170
"""Internal server error."""
171
error: str = "server_error"
172
status_code: int = 500
173
174
class TemporarilyUnavailableError(OAuth2Error):
175
"""Service temporarily unavailable."""
176
error: str = "temporarily_unavailable"
177
status_code: int = 503
178
```
179
180
### Security Errors
181
182
Security-related errors and policy violations.
183
184
```python { .api }
185
class InsecureTransportError(OAuth2Error):
186
"""HTTPS required."""
187
error: str = "invalid_request"
188
description: str = "HTTPS is required"
189
```
190
191
### OAuth 1.0 Exceptions
192
193
OAuth 1.0 specific error types.
194
195
```python { .api }
196
class OAuth1Error(Exception):
197
"""Base OAuth 1.0 exception."""
198
error: str
199
description: str
200
uri: str | None
201
status_code: int
202
203
def in_uri(self, uri: str) -> str: ...
204
205
@property
206
def twotuples(self) -> list[tuple[str, str]]: ...
207
208
@property
209
def urlencoded(self) -> str: ...
210
211
class InvalidSignatureMethodError(OAuth1Error):
212
"""Invalid signature method."""
213
error: str = "invalid_signature_method"
214
```
215
216
### OpenID Connect Exceptions
217
218
OpenID Connect specific error types.
219
220
```python { .api }
221
class InteractionRequired(OAuth2Error):
222
"""User interaction required."""
223
error: str = "interaction_required"
224
225
class LoginRequired(OAuth2Error):
226
"""User login required."""
227
error: str = "login_required"
228
229
class ConsentRequired(OAuth2Error):
230
"""User consent required."""
231
error: str = "consent_required"
232
233
class InvalidRequestObject(OAuth2Error):
234
"""Invalid request object."""
235
error: str = "invalid_request_object"
236
```
237
238
## Usage Examples
239
240
```python
241
from oauthlib.oauth2 import OAuth2Error, InvalidClientError, AccessDeniedError
242
243
# Handle OAuth errors in server
244
try:
245
# OAuth processing...
246
pass
247
except OAuth2Error as e:
248
return Response(
249
e.json,
250
status=e.status_code,
251
headers=e.headers
252
)
253
254
# Custom error handling
255
def handle_oauth_error(error):
256
if isinstance(error, InvalidClientError):
257
log_security_event("Invalid client authentication", error)
258
elif isinstance(error, AccessDeniedError):
259
log_user_action("Authorization denied", error)
260
261
return {
262
'error': error.error,
263
'error_description': error.description,
264
'status_code': error.status_code
265
}
266
267
# Error in redirect URI
268
try:
269
# Authorization processing...
270
pass
271
except OAuth2Error as e:
272
if e.redirect_uri:
273
error_uri = e.in_uri(e.redirect_uri)
274
return redirect(error_uri)
275
else:
276
return Response(e.json, status=e.status_code)
277
```