Skip to content

Commit c8a01f5

Browse files
authored
Merge pull request #209 from kinde-oss/fix/oauth-callback-state-nonce
fix(auth): require OAuth callback state and validate ID token nonce
2 parents 3fe1664 + 514f840 commit c8a01f5

5 files changed

Lines changed: 466 additions & 35 deletions

File tree

‎kinde_fastapi/framework/fastapi_framework.py‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from fastapi.responses import RedirectResponse, HTMLResponse
44
from kinde_sdk.core.framework.framework_interface import FrameworkInterface
55
from kinde_sdk.auth.oauth import OAuth
6+
from kinde_sdk.core.exceptions import KindeLoginException
67
from ..middleware.framework_middleware import FrameworkMiddleware
78
import os
89
import uuid
@@ -183,15 +184,18 @@ async def callback(request: Request, code: Optional[str] = None, state: Optional
183184
except Exception as ex:
184185
return HTMLResponse(f"Error parsing reauth state: {str(ex)}", status_code=400)
185186

187+
# Reject before handle_redirect, which would consume the pending state
188+
if not code:
189+
return HTMLResponse("Authentication failed: Missing authorization code", status_code=400)
190+
186191
user_id = request.session.get('user_id') or str(uuid.uuid4())
187192

188193
try:
189194
assert self._oauth is not None
190195
await self._oauth.handle_redirect(code, user_id, state)
191-
except Exception as e:
192-
if "State not found" in str(e):
193-
return HTMLResponse("Error: State not found. Please check Kinde Python SDK documentation.\n" + str(e), status_code=500)
194-
raise e
196+
except KindeLoginException as e:
197+
# Missing, forged or stale callbacks are client errors, as in the Flask route
198+
return HTMLResponse(f"Authentication failed: {e}", status_code=400)
195199

196200
request.session['user_id'] = user_id
197201

‎kinde_sdk/auth/oauth.py‎

Lines changed: 42 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import requests
33
import logging
44
import time
5+
import jwt
56
from typing import Any, Dict, Optional
67
from urllib.parse import urlencode
78

@@ -514,13 +515,30 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] =
514515
Returns:
515516
Dict with user and token information
516517
"""
517-
# Verify state if provided
518-
if state:
519-
stored_state = self._session_manager.storage_manager.get("user:state")
520-
if not stored_state or state != stored_state.get("value"):
521-
self._logger.error("State mismatch in OAuth callback")
522-
raise KindeLoginException("Invalid state parameter")
523-
518+
storage = self._session_manager.storage_manager
519+
520+
# Verify state. A callback is only accepted for a login started by this
521+
# SDK in this session: a state must have been stored, and the callback
522+
# must present the same value. Missing state is rejected, not skipped.
523+
stored_state = storage.get("user:state")
524+
expected_state = stored_state.get("value") if stored_state else None
525+
if not expected_state or state != expected_state:
526+
self._logger.error("State mismatch in OAuth callback")
527+
raise KindeLoginException("Invalid state parameter")
528+
529+
# Every SDK-started login stores a nonce. Without it the ID token can't be
530+
# bound to this login, so reject before the code is redeemed.
531+
stored_nonce = storage.get("user:nonce")
532+
expected_nonce = stored_nonce.get("value") if stored_nonce else None
533+
if not expected_nonce:
534+
self._logger.error("No nonce stored for OAuth callback")
535+
raise KindeLoginException("Missing nonce for this login")
536+
537+
# State and nonce are single-use: consume them once they have been
538+
# validated, so they can't be replayed even if the rest of the flow fails.
539+
storage.delete("user:state")
540+
storage.delete("user:nonce")
541+
524542
# Get code verifier for PKCE
525543
code_verifier = None
526544
stored_code_verifier = self._session_manager.storage_manager.get("user:code_verifier")
@@ -536,6 +554,23 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] =
536554
except Exception as e:
537555
self._logger.error(f"Token exchange failed: {str(e)}")
538556
raise KindeTokenException(f"Failed to exchange code for tokens: {str(e)}") from e
557+
558+
# Verify the ID token nonce matches the one sent in the authorization request.
559+
# A response without an ID token is rejected too: otherwise a swapped code
560+
# from an authorization request without `openid` would skip this check.
561+
id_token = token_data.get("id_token")
562+
if not id_token:
563+
self._logger.error("Token response has no ID token")
564+
raise KindeLoginException("Missing ID token")
565+
try:
566+
# Signature not verified, as elsewhere in the SDK: the token comes
567+
# directly from the token endpoint over TLS
568+
id_token_claims = jwt.decode(id_token, options={"verify_signature": False})
569+
except jwt.PyJWTError as e:
570+
raise KindeLoginException("Invalid ID token") from e
571+
if id_token_claims.get("nonce") != expected_nonce:
572+
self._logger.error("Nonce mismatch in ID token")
573+
raise KindeLoginException("Invalid nonce in ID token")
539574

540575
# Store tokens
541576
user_info = {
@@ -562,13 +597,6 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] =
562597
logger=self._logger
563598
)
564599

565-
# Clean up state
566-
if state:
567-
self._session_manager.storage_manager.delete("user:state")
568-
569-
# Clean up nonce
570-
self._session_manager.storage_manager.delete("user:nonce")
571-
572600
return {
573601
"tokens": token_data,
574602
"user": user_details

0 commit comments

Comments
 (0)