Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
45 changes: 30 additions & 15 deletions kinde_sdk/auth/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import requests
import logging
import time
import jwt
from typing import Any, Dict, Optional
from urllib.parse import urlencode

Expand Down Expand Up @@ -515,14 +516,24 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] =
Returns:
Dict with user and token information
"""
# Verify state if provided
if state:
stored_state = self._session_manager.storage_manager.get("user:state")
self._logger.warning(f"stored_state: {stored_state}, state: {state}")
if not stored_state or state != stored_state.get("value"):
self._logger.error(f"State mismatch: received {state}, stored {stored_state}")
raise KindeLoginException("Invalid state parameter")

storage = self._session_manager.storage_manager

# Verify state. A callback is only accepted for a login started by this
# SDK in this session: a state must have been stored, and the callback
# must present the same value. Missing state is rejected, not skipped.
stored_state = storage.get("user:state")
expected_state = stored_state.get("value") if stored_state else None
if not expected_state or state != expected_state:
self._logger.error("State mismatch in OAuth callback")
raise KindeLoginException("Invalid state parameter")
Comment on lines +525 to +527

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This is the right rejection, and it happens before the token request. One caller does not surface it as a client error.

kinde_fastapi/framework/fastapi_framework.py (unchanged, so I can't comment on that line directly) only special-cases "State not found", which nothing in the SDK raises, then re-raises. The new message is Invalid state parameter, so FastAPI returns 500. Flask maps the same KindeLoginException to 400. Missing state is now the normal reject path, so forged and stale callbacks will show up as server errors. Map KindeLoginException to 400 in that route.

That FastAPI route also never requires code before handle_redirect. A request with a valid state and no code still deletes state, nonce, and the code verifier, then calls the token endpoint. Flask rejects a missing code first. The new route tests allow any status >= 400, so they pass on the 500.

@KomanRudden KomanRudden Oct 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The FastAPI callback now returns 400 for a missing code before calling handle_redirect, so the state, nonce and code verifier are kept, and returns 400 for KindeLoginException, matching Flask. The unused "State not found" branch is removed. The route tests now assert 400 exactly, and there is a missing-code test for both Flask and FastAPI.


# State and nonce are single-use: consume them once state has been
# validated, so they can't be replayed even if the rest of the flow fails.
stored_nonce = storage.get("user:nonce")
expected_nonce = stored_nonce.get("value") if stored_nonce else None
storage.delete("user:state")
storage.delete("user:nonce")

# Get code verifier for PKCE
code_verifier = None
stored_code_verifier = self._session_manager.storage_manager.get("user:code_verifier")
Expand All @@ -538,6 +549,17 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] =
except Exception as e:
self._logger.error(f"Token exchange failed: {str(e)}")
raise KindeTokenException(f"Failed to exchange code for tokens: {str(e)}") from e

# Verify the ID token nonce matches the one sent in the authorization request
id_token = token_data.get("id_token")
if expected_nonce and id_token:
try:
id_token_claims = jwt.decode(id_token, options={"verify_signature": False})
except jwt.PyJWTError as e:
raise KindeLoginException("Invalid ID token") from e
if id_token_claims.get("nonce") != expected_nonce:
self._logger.error("Nonce mismatch in ID token")
raise KindeLoginException("Invalid nonce in ID token")

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This check runs only when both a stored nonce and an id_token are present. A token response with no id_token skips it and still reaches set_user_data. A missing or empty user:nonce does the same, so losing that one key turns nonce validation off while state validation stays on.

That is the gap state does not cover: someone keeps the victim's state and swaps the code. PKCE stops that when this SDK stored a verifier. It does not when the caller passed code_challenge (user:code_verifier is never written), or when the token endpoint redeems a confidential client without a verifier. The token response is then for the attacker's authorization request. If that request did not include openid, there is no id_token, userinfo runs with their access token, and the victim's session is created as the attacker.

generate_auth_url always sends a nonce, including for the default openid profile email scope. When expected_nonce is set, reject the response if id_token is absent or its nonce claim does not match. Treat a missing stored nonce as a failure too.

jwt.decode(..., verify_signature=False) matches token_manager.py and is fine on PyJWT 2.10. It is safe only because this token came from the token endpoint over TLS. Anyone who can supply that response can forge the nonce claim. test_token_response_without_id_token_still_accepted currently locks the skip in; that test needs to expect a rejection if this changes.

@KomanRudden KomanRudden Oct 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

A missing stored nonce is now rejected before the token request, and a token response without an id_token is rejected. test_token_response_without_id_token_still_accepted is now test_token_response_without_id_token_rejected and expects the rejection, and there is a new test for the missing stored nonce.


# Store tokens
user_info = {
Expand Down Expand Up @@ -565,13 +587,6 @@ async def handle_redirect(self, code: str, user_id: str, state: Optional[str] =
logger=self._logger
)

# Clean up state
if state:
self._session_manager.storage_manager.delete("user:state")

# Clean up nonce
self._session_manager.storage_manager.delete("user:nonce")

return {
"tokens": token_data,
"user": user_details
Expand Down
Loading
Loading