fix(auth): get_access_token reflects current request in stateful sessions

Closed
EP
1mo ago
+181-1

Fixes #2208.

Stateful Streamable HTTP sessions start the server task group on the first request. Anyio copies the request contextvars into that long-lived task, so get_access_token() could keep returning the token from the session-creating request even when later requests send a different Authorization header.

This change pushes the authenticated user into the auth contextvar at request-dispatch time (using the ServerMessageMetadata.request_context threaded through the transport), and resets it after the handler returns.

Tests:

  • uv run python -m pytest tests/server/auth/middleware/test_auth_context.py tests/server/auth/test_get_access_token_streamable_http.py