Repository navigation
fix(auth): require OAuth callback state and validate ID token nonce #209
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
445f44c
ad0c2ee
2a2c7aa
514f840
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -2,6 +2,7 @@ | |
| import requests | ||
| import logging | ||
| import time | ||
| import jwt | ||
| from typing import Any, Dict, Optional | ||
| from urllib.parse import urlencode | ||
|
|
||
|
|
@@ -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") | ||
|
|
||
| # 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") | ||
|
|
@@ -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") | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This check runs only when both a stored nonce and an That is the gap state does not cover: someone keeps the victim's
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 |
||
|
|
||
| # Store tokens | ||
| user_info = { | ||
|
|
@@ -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 | ||
|
|
||
There was a problem hiding this comment.
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 isInvalid state parameter, so FastAPI returns 500. Flask maps the sameKindeLoginExceptionto 400. Missing state is now the normal reject path, so forged and stale callbacks will show up as server errors. MapKindeLoginExceptionto 400 in that route.That FastAPI route also never requires
codebeforehandle_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.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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
codebefore callinghandle_redirect, so the state, nonce and code verifier are kept, and returns 400 forKindeLoginException, 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.