Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
ff4c63f
chore: Resolves Issue #92, updates to use transitive dependency explicit
blochs Sep 29, 2026
202832c
Merge auth0 upstream main and resolve joserfc migration conflicts
blochs Oct 29, 2026
2337e5a
fix: preserve Python 3.9 compatibility in JOSE migration
blochs Oct 29, 2026
d13849d
refactor: centralize Python-version JOSE backend selection
blochs Oct 30, 2026
501d1d2
fix: declare joserfc dependency and clarify JWT configuration
blochs Oct 30, 2026
e67688e
fix: declare joserfc dependency and clarify JWT configuration
blochs Oct 30, 2026
0e9d19b
fix: declare joserfc dependency and clarify JWT configuration
blochs Oct 30, 2026
b32f14f
fix: validate JWT algorithms and JWKS metadata, normalize verificatio…
blochs Oct 30, 2026
42e209b
test: support alternate JWT algorithms without production JWS registr…
blochs Oct 30, 2026
7782e9e
test: cover algorithm restrictions, cross-runtime JWKS behavior and D…
blochs Oct 30, 2026
529128c
docs: explain JOSE compatibility and JWT algorithm constraints
blochs Oct 30, 2026
b4ed67e
docs: explain JOSE compatibility and JWT algorithm constraints
blochs Oct 30, 2026
b80c5c9
build: refresh Poetry lock content hash for explicit joserfc dependency
blochs Oct 30, 2026
02e40bb
style: clarify Python 3.9 JOSE fallback comment
blochs Oct 30, 2026
bf1acef
chore: merge upstream/main, drop Python 3.9/authlib fallback, fix jos…
blochs Nov 21, 2026
2af9a4e
chore(deps): bump joserfc floor to >=1.7.6,<2.0 (locks 1.7.7) to reso…
blochs Nov 21, 2026
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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,19 @@
# Change Log
## Unreleased

**Changed**
- Migrated JOSE operations from `authlib.jose` to `joserfc` across all supported
Python versions (3.10+) and dropped the unused `authlib` dependency.
- Added configurable `jwt_algorithms` for access-token signatures (default
`RS256`); only recognized asymmetric algorithms are accepted, and JWKS `alg`
restrictions are enforced.
- Decoded access-token and DPoP claims are returned as plain dictionaries.
`joserfc` validates JOSE header names/types, header and payload sizes, and
key `use`, `key_ops`, and `alg` metadata more strictly than legacy Authlib.
Incompatible tokens or keys may require migration.
- Malformed DPoP proof payloads and unusable JWKS keys now raise SDK-specific
verification errors instead of exposing lower-level exceptions.


## [1.0.0b11](https://github.com/auth0/auth0-api-python/tree/1.0.0b11) (2026-11-11)
[Full Changelog](https://github.com/auth0/auth0-api-python/compare/1.0.0b10...1.0.0b11)
Expand Down
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,33 @@ This SDK provides comprehensive support for securing APIs with Auth0-issued acce
- **Framework Agnostic** - Works with FastAPI, Django, Flask, or any Python web framework

## Documentation
## JWT algorithms and `joserfc` validation

Access-token verification accepts `RS256` by default. To allow another asymmetric
signature algorithm, supply `jwt_algorithms` when constructing `ApiClientOptions`:

```python
ApiClientOptions(
domain="example.us.auth0.com",
audience="my-api",
jwt_algorithms=["RS256", "RS384"],
)
```

The list must be non-empty and contain supported `RS*`, `PS*`, or `ES*` algorithms.
Symmetric (`HS*`), unsigned (`none`), and unrecognized algorithms are rejected at
construction. The configuration is copied when the client is constructed. The JWT's
declared algorithm must also match any `alg` restriction set on the selected JWKS
key; configuring `RS384` does not override a key declared for `RS256`. A tenant
that issues RS384 tokens must publish an RS384-capable key.

JOSE operations use `joserfc` directly. Decoded access-token and DPoP claims are
returned as plain dictionaries, and invalid key material produces SDK verification
errors. `joserfc` enforces strict validation of JOSE headers (including registered
header names and their types), encoded header/payload sizes, and JWK usage
restrictions (`use`, `key_ops`, and `alg`). DPoP remains restricted to `ES256`
regardless of `jwt_algorithms`.


- [Docs Site](https://auth0.com/docs) - explore our docs site and learn more about Auth0.

Expand Down
28 changes: 6 additions & 22 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ packages = [

[tool.poetry.dependencies]
python = ">=3.10"
authlib = "^1.0" # For JWT/OIDC features
joserfc = ">=1.7.6,<2.0"
requests = "^2.31.0" # If you use requests for HTTP calls (e.g., discovery)
httpx = "^0.28.1"
cryptography = ">=43.0.1"
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# This file is maintained manually for SCA scanning (.github/workflows/sca_scan.yml)
# Source of truth for dependencies: pyproject.toml + poetry.lock

authlib>=1.6.12
joserfc>=1.7.6,<2.0
httpx>=0.28.1
ada-url>=1.32.0
pytest>=8.0
Expand Down
47 changes: 37 additions & 10 deletions src/auth0_api_python/api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from typing import Any

import httpx
from authlib.jose import JsonWebKey, JsonWebToken
from joserfc import jwk, jwt

from ._internal.cache_expiry import is_fresh
from ._internal.cache_keys import m2m_cache_key
Expand Down Expand Up @@ -51,6 +51,14 @@

logger = logging.getLogger(__name__)

# Access tokens must use a supported asymmetric signature algorithm.
# Never allow "none" (unsigned JWTs) or symmetric algorithms with public JWKS keys.
SUPPORTED_JWT_ALGORITHMS = frozenset({
"RS256", "RS384", "RS512",
"PS256", "PS384", "PS512",
"ES256", "ES384", "ES512",
})

# Token Exchange constants
TOKEN_EXCHANGE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange" # noqa: S105
OBO_ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token" # noqa: S105
Expand Down Expand Up @@ -78,6 +86,17 @@ def __init__(self, options: ApiClientOptions):
if not options.audience:
raise MissingRequiredArgumentError("audience")

if not isinstance(options.jwt_algorithms, list) or not options.jwt_algorithms:
raise ConfigurationError("jwt_algorithms must be a non-empty list")
for algorithm in options.jwt_algorithms:
if not isinstance(algorithm, str) or algorithm not in SUPPORTED_JWT_ALGORITHMS:
raise ConfigurationError(
f"Unsupported JWT signing algorithm: {algorithm!r}. "
"Only RS*, PS*, and ES* asymmetric algorithms are supported."
)
# Do not allow mutation of the caller's list to change accepted algorithms.
self._jwt_algorithms = list(options.jwt_algorithms)

# Validate domains parameter if provided
if options.domains is not None:
if isinstance(options.domains, list):
Expand Down Expand Up @@ -190,10 +209,7 @@ def __init__(self, options: ApiClientOptions):

self._cache_ttl = options.cache_ttl_seconds

self._jwt = JsonWebToken(["RS256"])

self._dpop_algorithms = ["ES256"]
self._dpop_jwt = JsonWebToken(self._dpop_algorithms)

def is_dpop_required(self) -> bool:
"""Check if DPoP authentication is required."""
Expand Down Expand Up @@ -481,7 +497,7 @@ async def verify_access_token(
Asynchronously verifies the provided JWT access token.

- Fetches OIDC metadata and JWKS if not already cached.
- Decodes and validates signature (RS256) with the correct key.
- Decodes and validates the signature with the configured jwt_algorithms (default RS256).
- Checks standard claims: 'iss', 'aud', 'exp', 'nbf', 'iat'
- Checks extra required claims if 'required_claims' is provided.
- Enforces organization_policy: requires 'org_id' when set to "required",
Expand Down Expand Up @@ -524,6 +540,8 @@ async def verify_access_token(
f"Symmetric algorithm '{alg}' is not supported. "
"Only asymmetric algorithms (e.g., RS256) are allowed."
)
if alg not in self._jwt_algorithms:
raise VerifyAccessTokenError(f"JWT signing algorithm '{alg}' is not allowed")

# Extract and validate issuer claim (before network calls)
try:
Expand Down Expand Up @@ -610,13 +628,19 @@ async def verify_access_token(
if not matching_key_dict:
raise VerifyAccessTokenError("No matching key found in JWKS")

# Import public key and verify signature
public_key = JsonWebKey.import_key(matching_key_dict)
# Respect the key's declared algorithm so a JWKS key for RS256 cannot verify an RS384 token.
key_alg = matching_key_dict.get("alg")
if key_alg is not None and key_alg != alg:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once 3.9 is dropped this check isn't needed, because joserfc already rejects a token whose alg differs from the key's alg (with unsupported_key_alg). It only changes the outcome on the Authlib path. We can keep it if we prefer the shorter SDK message, WDYT?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept this check for now since the SDK message (JWT algorithm does not match JWKS key algorithm) is clearer than joserfcs unsupported_key_alg, and removed the 3.9 comment. Happy to drop it if you prefer.

raise VerifyAccessTokenError("JWT algorithm does not match JWKS key algorithm")

if isinstance(access_token, str) and access_token.startswith("b'"):
access_token = access_token[2:-1]
try:
claims = self._jwt.decode(access_token, public_key)
public_key = jwk.import_key(matching_key_dict)
claims = jwt.decode(access_token, public_key, algorithms=self._jwt_algorithms).claims
if not isinstance(claims, dict):
raise ValueError("JWT payload is not a JSON object")
claims = dict(claims)
except Exception as e:
raise VerifyAccessTokenError(f"Signature verification failed: {str(e)}") from e

Expand Down Expand Up @@ -712,15 +736,18 @@ async def verify_dpop_proof(
raise InvalidDpopProofError("Only P-256 curve is supported")

try:
public_key = JsonWebKey.import_key(jwk_dict)
public_key = jwk.import_key(jwk_dict)
except Exception:
raise InvalidDpopProofError("Missing or invalid jwk in header")

try:
claims = self._dpop_jwt.decode(proof, public_key)
claims = jwt.decode(proof, public_key, algorithms=self._dpop_algorithms).claims
except Exception as e:
raise InvalidDpopProofError(f"JWT signature verification failed: {e}")

if not isinstance(claims, dict):
raise InvalidDpopProofError("DPoP proof payload must be a JSON object")

# Checks all required claims are present
self._validate_claims_presence(claims, ["iat", "ath", "htm", "htu", "jti"])

Expand Down
5 changes: 5 additions & 0 deletions src/auth0_api_python/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ class ApiClientOptions:
the request, and requires a token_store subclassing IndexedTokenStore
(raises ConfigurationError at construction without one).
client_info: Name, version and optional env of a wrapper SDK built on this one, as a dict with non-empty string "name" and "version" keys and an optional "env" dict of string keys and values. Sent in the Auth0-Client header. An invalid value raises ConfigurationError at construction, and the "python" and "auth0-api-python" entries in env are set by this SDK.
jwt_algorithms: Non-empty list of supported asymmetric JWT signing algorithms.
Defaults to ["RS256"]; unknown, symmetric, and unsigned algorithms
raise ConfigurationError at ApiClient construction.
"""
def __init__(
self,
Expand All @@ -71,10 +74,12 @@ def __init__(
organization_id: str | list[str] | None = None,
scope_matching: str = "strict",
client_info: dict | None = None,
jwt_algorithms: list[str] | None = None,
):
self.domain = domain
self.domains = domains
self.audience = audience
self.jwt_algorithms = ["RS256"] if jwt_algorithms is None else jwt_algorithms
self.custom_fetch = custom_fetch
self.cache_adapter = cache_adapter
self.token_store = token_store
Expand Down
34 changes: 23 additions & 11 deletions src/auth0_api_python/token_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
import uuid
from typing import Any

from authlib.jose import JsonWebKey, jwt
from joserfc import jwk, jwt
from joserfc.jws import JWSRegistry
from joserfc.registry import HeaderParameter

from .utils import calculate_jwk_thumbprint, normalize_url_for_htu, sha256_base64url

Expand Down Expand Up @@ -33,9 +35,10 @@ async def generate_token(
exp: bool = True,
claims: dict[str, Any] | None = None,
expiration_time: int = 3600,
algorithm: str = "RS256",
) -> str:
"""
Generates a real RS256-signed JWT using the private key above.
Generates a signed JWT using the private key above.

Args:
domain: The Auth0 domain (used if issuer is not False).
Expand All @@ -49,9 +52,10 @@ async def generate_token(
exp: Whether to set the 'exp' claim. If False, skip it.
claims: Additional custom claims to merge into the token.
expiration_time: If exp is True, how many seconds from now until expiration.
algorithm: Signing algorithm (default RS256); tests may use RS384, for example.

Returns:
A RS256-signed JWT string.
A signed JWT string.

Example usage:
token = generate_token(
Expand Down Expand Up @@ -80,10 +84,11 @@ async def generate_token(
token_claims["aud"] = audience


key = JsonWebKey.import_key(PRIVATE_JWK)
key_data = {**PRIVATE_JWK, "alg": algorithm}
key = jwk.import_key(key_data)

header = {"alg": "RS256", "kid": PRIVATE_JWK["kid"]}
token = jwt.encode(header, token_claims, key)
header = {"alg": algorithm, "kid": PRIVATE_JWK["kid"]}
Comment thread
blochs marked this conversation as resolved.
Resolved
token = jwt.encode(header, token_claims, key, algorithms=[algorithm])
# Ensure we return a string, not bytes
return token.decode('utf-8') if isinstance(token, bytes) else token

Expand Down Expand Up @@ -163,13 +168,20 @@ async def generate_dpop_proof(
}


key = jwk.import_key(PRIVATE_EC_JWK)

if header_overrides:
header.update(header_overrides)

key = JsonWebKey.import_key(PRIVATE_EC_JWK)
token = jwt.encode(header, proof_claims, key)
# Ensure we return a string, not bytes
return token.decode('utf-8') if isinstance(token, bytes) else token
registry = JWSRegistry(
header_registry={
name: HeaderParameter("header override", lambda _: None)
for name in header_overrides
}
)
token = jwt.encode(header, proof_claims, key, registry=registry)
else:
token = jwt.encode(header, proof_claims, key)
return token.decode("utf-8") if isinstance(token, bytes) else token


async def generate_token_with_cnf(
Expand Down
Loading