Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions EXAMPLES.md
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,23 @@ headers = {"authorization": "Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..."}
result = asyncio.run(validate_request(headers))
```

### Telling an Outage from an Invalid Token

`AuthServerUnavailableError` is raised when the discovery document or JWKS cannot be reached. It subclasses `VerifyAccessTokenError`, so catch it first to answer `503` instead of `401`.

```python
from auth0_api_python import ApiClient, AuthServerUnavailableError, VerifyAccessTokenError

async def validate_token(api_client: ApiClient, token: str):
try:
claims = await api_client.verify_access_token(token)
return {"success": True, "user": claims["sub"]}
except AuthServerUnavailableError as e:
return {"error": e.get_error_code()}, e.get_status_code() # 503, retry later
except VerifyAccessTokenError as e:
return {"error": e.get_error_code()}, e.get_status_code() # 401, token rejected
```


## DPoP Authentication

Expand Down
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,12 @@ asyncio.run(main())

In this example, the returned dictionary contains the decoded claims (like `sub`, `scope`, etc.) from the verified token.

If the OIDC discovery document or the JWKS request cannot be reached (connection error, timeout, or an HTTP `5xx` or `429` response), the method raises `AuthServerUnavailableError`, a subclass of `VerifyAccessTokenError` with status `503` and error code `auth_server_unavailable`. Other fetch failures, such as a `404` or a malformed response, still raise `VerifyAccessTokenError`. `verify_request()` raises the same error and sets no `WWW-Authenticate` header, so clients retry later instead of requesting a new token.

HTTP status codes are checked only for the default HTTP client. With `custom_fetch`, only a connection error or timeout raised by your function is reported as `AuthServerUnavailableError`.

This error comes from token verification only. Where verification is skipped, such as `get_client_credentials_token()` or an exchange with `verified=`, a failed discovery request raises the underlying `httpx` error.

### 4. Get an access token for a connection

If you need to get an access token for an upstream idp via a connection, you can use the `get_access_token_for_connection` method:
Expand Down
2 changes: 2 additions & 0 deletions docs/MultipleCustomDomain.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,8 @@ except VerifyAccessTokenError as e:
e.get_headers() # {"WWW-Authenticate": "Bearer error=\"invalid_token\", ..."}
```

If the discovery document or JWKS of an allowed domain cannot be reached, `verify_access_token()` raises `AuthServerUnavailableError` (a `VerifyAccessTokenError` subclass, status `503`, code `auth_server_unavailable`) instead of a 401.

---

## Migration Guide
Expand Down
2 changes: 2 additions & 0 deletions src/auth0_api_python/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from .config import ApiClientOptions
from .errors import (
ApiError,
AuthServerUnavailableError,
ConfigurationError,
DomainsResolverError,
GetAccessTokenForConnectionError,
Expand Down Expand Up @@ -38,6 +39,7 @@
"ApiClient",
"ApiClientOptions",
"ApiError",
"AuthServerUnavailableError",
"CacheAdapter",
"ClientCredentialsTokenResult",
"ConfigurationError",
Expand Down
16 changes: 14 additions & 2 deletions src/auth0_api_python/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from .config import ApiClientOptions
from .errors import (
ApiError,
AuthServerUnavailableError,
BaseAuthError,
ConfigurationError,
DomainsResolverError,
Expand All @@ -39,6 +40,7 @@
fetch_oidc_metadata,
get_unverified_header,
get_unverified_payload,
is_auth_server_outage,
normalize_domain,
normalize_url_for_htu,
sha256_base64url,
Expand Down Expand Up @@ -306,6 +308,7 @@ async def verify_request(
InvalidAuthSchemeError: If an unsupported scheme is provided
InvalidDpopProofError: If DPoP verification fails
VerifyAccessTokenError: If access token verification fails
AuthServerUnavailableError: If the OIDC discovery document or JWKS cannot be reached
"""
# Normalize header keys to lowercase for robust access
headers = {k.lower(): v for k, v in headers.items()}
Expand Down Expand Up @@ -489,6 +492,7 @@ async def verify_access_token(
DomainsResolverError: If domains resolver function fails.
MissingOrganizationError: If organization_policy is "required" and the token has no org_id claim.
OrganizationNotAllowedError: If the token's org_id is not in the organization_id allowlist.
AuthServerUnavailableError: If the OIDC discovery document or JWKS cannot be reached.
"""
if not access_token:
raise MissingRequiredArgumentError("access_token")
Expand Down Expand Up @@ -542,7 +546,8 @@ async def verify_access_token(
except VerifyAccessTokenError:
raise
except Exception as e:
raise VerifyAccessTokenError(
error_class = AuthServerUnavailableError if is_auth_server_outage(e) else VerifyAccessTokenError
raise error_class(
f"Failed to fetch OIDC discovery metadata: {str(e)}"
) from e

Expand Down Expand Up @@ -573,7 +578,8 @@ async def verify_access_token(
except VerifyAccessTokenError:
raise
except Exception as e:
raise VerifyAccessTokenError(
error_class = AuthServerUnavailableError if is_auth_server_outage(e) else VerifyAccessTokenError
raise error_class(
f"Failed to fetch JWKS: {str(e)}"
) from e

Expand Down Expand Up @@ -754,6 +760,7 @@ async def get_access_token_for_connection(
VerifyAccessTokenError: If a store is configured and either verified is omitted and the token fails verification, or verified is supplied but does not match the access token being exchanged.
MissingOrganizationError: If a store is configured, verified is omitted, organization_policy is "required" and the token has no org_id claim.
OrganizationNotAllowedError: If a store is configured, verified is omitted and the token's org_id is not in the organization_id allowlist.
AuthServerUnavailableError: If a store is configured, verified is omitted and the OIDC discovery document or JWKS cannot be reached.

Returns:
Dictionary containing the token response with access_token, expires_in, and scope.
Expand Down Expand Up @@ -1125,6 +1132,7 @@ async def get_token_on_behalf_of(
VerifyAccessTokenError: If a store is configured and either verified is omitted and the token fails verification, or verified is supplied but does not match the access token being exchanged
MissingOrganizationError: If a store is configured, verified is omitted, organization_policy is "required" and the token has no org_id claim
OrganizationNotAllowedError: If a store is configured, verified is omitted and the token's org_id is not in the organization_id allowlist
AuthServerUnavailableError: If a store is configured, verified is omitted and the OIDC discovery document or JWKS cannot be reached
GetTokenByExchangeProfileError: If client credentials are not configured or validation fails
ApiError: If the token endpoint returns an error
"""
Expand Down Expand Up @@ -1477,6 +1485,10 @@ def _prepare_error(self, error: BaseAuthError, auth_scheme: Optional[str] = None
error: The error to prepare
auth_scheme: The authentication scheme that was used ("bearer" or "dpop")
"""
if error.get_status_code() >= 500:
error._headers = {}
return error

error_code = error.get_error_code()
error_description = error.get_error_description()

Expand Down
10 changes: 10 additions & 0 deletions src/auth0_api_python/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ def get_error_code(self) -> str:
return "invalid_token"


class AuthServerUnavailableError(VerifyAccessTokenError):
"""Error raised when the OIDC discovery document or JWKS cannot be reached."""

def get_status_code(self) -> int:
return 503

def get_error_code(self) -> str:
return "auth_server_unavailable"


class MissingOrganizationError(VerifyAccessTokenError):
"""Error raised when organization_policy is 'required' but the token has no org_id claim."""

Expand Down
20 changes: 20 additions & 0 deletions src/auth0_api_python/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using httpx or a custom fetch approach.
"""

import asyncio
import base64
import hashlib
import json
Expand Down Expand Up @@ -82,6 +83,25 @@ def normalize_domain(domain: str) -> str:
return f"https://{host}/"


def is_auth_server_outage(error: Exception) -> bool:
"""
Check whether a discovery or JWKS fetch error means the auth server is down or overloaded.

Args:
error: The exception raised while fetching.

Returns:
True for connection errors, timeouts, HTTP 5xx and HTTP 429. False for anything else.
"""
if isinstance(error, httpx.HTTPStatusError):
status = error.response.status_code
return status >= 500 or status == 429
return isinstance(
error,
(httpx.NetworkError, httpx.TimeoutException, ConnectionError, TimeoutError, asyncio.TimeoutError),
)


async def fetch_oidc_metadata(
domain: str,
custom_fetch: Optional[Callable[..., Any]] = None
Expand Down
Loading
Loading