Skip to content

Commit b359b0e

Browse files
committed
Add HTTP status check before parsing token responses
- Prevents misleading 'Missing access_token parameter' errors when server returns HTTP errors. - Properly raises HTTPError with the actual error message received from the server for 4xx/5xx responses.
1 parent f33dac3 commit b359b0e

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

requests_oauthlib/oauth2_session.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError
55
from oauthlib.oauth2 import LegacyApplicationClient
66
from oauthlib.oauth2 import TokenExpiredError, is_secure_transport
7+
from oauthlib.oauth2.rfc6749.errors import CustomOAuth2Error
78
import requests
89

910
log = logging.getLogger(__name__)
@@ -199,6 +200,17 @@ def authorization_url(self, url, state=None, **kwargs):
199200
state,
200201
)
201202

203+
def validate_token_response(self, r):
204+
message = ""
205+
try:
206+
r.raise_for_status()
207+
except requests.HTTPError as e:
208+
message = str(e)
209+
if r.text:
210+
message += f"\nBody: {r.text}"
211+
if message:
212+
raise CustomOAuth2Error('Response error', message, uri=r.request.url, status_code=r.status_code)
213+
202214
def fetch_token(
203215
self,
204216
token_url,
@@ -403,6 +415,7 @@ def fetch_token(
403415
log.debug("Invoking hook %s.", hook)
404416
r = hook(r)
405417

418+
self.validate_token_response(r)
406419
self._client.parse_request_body_response(r.text, scope=self.scope)
407420
self.token = self._client.token
408421
log.debug("Obtained token %s.", self.token)
@@ -493,6 +506,7 @@ def refresh_token(
493506
log.debug("Invoking hook %s.", hook)
494507
r = hook(r)
495508

509+
self.validate_token_response(r)
496510
self.token = self._client.parse_request_body_response(r.text, scope=self.scope)
497511
if "refresh_token" not in self.token:
498512
log.debug("No new refresh token given. Re-using old.")

0 commit comments

Comments
 (0)