{"record":{"id":"093f7d7c15bc2739","repo":"microsoft/semantic-kernel","slug":"invalid-authorization-code","errorCode":null,"errorMessage":"Invalid authorization code","messagePattern":"Invalid authorization code","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/samples/demos/mcp_with_oauth/server/mcp_simple_auth/simple_auth_provider.py","lineNumber":212,"sourceCode":"            \"user_id\": f\"user_{secrets.token_hex(8)}\",\n            \"authenticated_at\": time.time(),\n        }\n\n        del self.state_mapping[state]\n        return construct_redirect_uri(redirect_uri, code=new_code, state=state)\n\n    async def load_authorization_code(\n        self, client: OAuthClientInformationFull, authorization_code: str\n    ) -> AuthorizationCode | None:\n        \"\"\"Load an authorization code.\"\"\"\n        return self.auth_codes.get(authorization_code)\n\n    async def exchange_authorization_code(\n        self, client: OAuthClientInformationFull, authorization_code: AuthorizationCode\n    ) -> OAuthToken:\n        \"\"\"Exchange authorization code for tokens.\"\"\"\n        if authorization_code.code not in self.auth_codes:\n            raise ValueError(\"Invalid authorization code\")\n\n        # Generate MCP access token\n        mcp_token = f\"mcp_{secrets.token_hex(32)}\"\n\n        # Store MCP token\n        self.tokens[mcp_token] = AccessToken(\n            token=mcp_token,\n            client_id=client.client_id,\n            scopes=authorization_code.scopes,\n            expires_at=int(time.time()) + 3600,\n            resource=authorization_code.resource,  # RFC 8707\n        )\n\n        # Store user data mapping for this token\n        self.user_data[mcp_token] = {\n            \"username\": self.settings.demo_username,\n            \"user_id\": f\"user_{secrets.token_hex(8)}\",\n            \"authenticated_at\": time.time(),","sourceCodeStart":194,"sourceCodeEnd":230,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/samples/demos/mcp_with_oauth/server/mcp_simple_auth/simple_auth_provider.py#L194-L230","documentation":"Raised during the OAuth token exchange step: the authorization code passed to exchange_authorization_code is not present in self.auth_codes. Authorization codes in this sample are single-use (deleted immediately after exchange at line 233) and held only in memory, so the code is rejected if it was already used, expired, or generated by a different server instance.","triggerScenarios":"Calling the token endpoint twice with the same code (second call fails because the first deleted it); server restart wiping the in-memory auth_codes; presenting a code issued by a previous/other server instance; replaying a captured code.","commonSituations":"MCP client retries the token request after a transient network error (code already consumed); server restarted between authorization and token exchange; running the flow across server redeployments.","solutions":["Restart the OAuth flow from the beginning to get a brand-new authorization code, and exchange it exactly once.","Avoid server restarts between issuing and exchanging the code (in-memory store).","Make the MCP client start a fresh authorization request after any failed token exchange rather than retrying the same code.","Run a single server instance; do not load-balance the sample across processes."],"exampleFix":"// Operational, not a code fix. Exchange each code exactly once:\n// 1. authorize -> get code\n// 2. exchange code -> tokens (one-shot)\n// 3. on any failure, restart from step 1","handlingStrategy":"validation","validationCode":"# Exchange each authorization code exactly once; track whether it was consumed.\nif code not in provider.auth_codes:\n    # restart the authorization flow to obtain a fresh code\n    raise RuntimeError('code already consumed or invalid; restart flow')","typeGuard":null,"tryCatchPattern":"try:\n    token = await provider.exchange_authorization_code(client, auth_code)\nexcept ValueError as e:\n    if 'Invalid authorization code' in str(e):\n        # begin a new authorization request; do not retry the same code\n        ...\n    raise","preventionTips":["Never retry a token exchange with the same code after any failure.","Keep the server running between code issuance and exchange (in-memory store).","Run a single server instance for the sample.","On any token-endpoint error, restart the flow from authorization."],"tags":["oauth","mcp","authentication","authorization-code","demo"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}