The Fix
Upgrade to version 0.20.1 or later.
Based on closed Kludex/starlette issue #1362 · PR/commit linked
Production note: Most teams hit this during upgrades or environment changes. Roll out with a canary and smoke critical endpoints (health, OpenAPI/docs) before 100%.
@@ -115,6 +115,10 @@ async def dashboard(request):
```
+!!! note
+ The `status_code` parameter is not supported with WebSockets. The 403 (Forbidden)
+ status code will always be used for those.
import uvicorn
from starlette.applications import Starlette
from starlette.authentication import AuthenticationBackend, AuthenticationError, AuthCredentials, SimpleUser, requires
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.websockets import WebSocket
class BasicAuthBackend(AuthenticationBackend):
async def authenticate(self, request):
auth = request.headers.get("Authorization", None)
if auth != 'sample_key':
raise AuthenticationError('Invalid auth credentials')
return AuthCredentials(["authenticated"]), SimpleUser("username")
app = Starlette(
middleware=[
Middleware(AuthenticationMiddleware, backend=BasicAuthBackend()),
],
)
@app.websocket_route("/websocket")
@requires("authenticated", status_code=401)
async def websocket(websocket: WebSocket):
await websocket.accept()
await websocket.send_json({'message': 'Connected and authenticated!'})
await websocket.close()
if __name__ == '__main__':
uvicorn.run("websocket:app", host="0.0.0.0", port=10123)
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.
Option A — Upgrade to fixed release\nUpgrade to version 0.20.1 or later.\nWhen NOT to use: This fix is not applicable if the application requires custom WebSocket status codes.\n\n
Why This Fix Works in Production
- Trigger: If the authentication check fails, the response code from the websocket is `403 Forbidden`, but it should be `401 Unauthorized`.
- Mechanism: The WebSocket authentication decorator does not properly handle unauthorized status codes
- Why the fix works: Documented that the `status_code` parameter is not supported with WebSockets, which will always return a 403 status code. (first fixed release: 0.20.1).
- If left unfixed, the same config can fail only in production (env differences), causing startup failures or partial feature outages.
Why This Breaks in Prod
- The WebSocket authentication decorator does not properly handle unauthorized status codes
- Production symptom (often without a traceback): If the authentication check fails, the response code from the websocket is `403 Forbidden`, but it should be `401 Unauthorized`.
Proof / Evidence
- GitHub issue: #1362
- Fix PR: https://github.com/kludex/starlette/pull/1636
- First fixed release: 0.20.1
- Reproduced locally: No (not executed)
- Last verified: 2026-02-09
- Confidence: 0.85
- Did this fix it?: Yes (upstream fix exists)
- Own content ratio: 0.44
Discussion
High-signal excerpts from the issue thread (symptoms, repros, edge-cases).
“I guess they are related, they point to the same code but not exactly the same issue. I think this issue is here where we…”
“I'm not 100% sure but after checking the code I think this might be happening In Uvicorn. What do you think @Kludex ? https://github.com/encode/uvicorn/blob/65ec8d132c37a8338a2f495fa1be9f14bd4368d9/uvicorn/protocols/websockets/websockets_impl.py#L236-L244”
“Is it related to this? https://github.com/encode/uvicorn/issues/1181”
“I think this should probably be discussed in Uvicorn, but out of curiosity I've checked daphne websocket, and they're doing the same thing here: The…”
Failure Signature (Search String)
- If the authentication check fails, the response code from the websocket is `403 Forbidden`, but it should be `401 Unauthorized`.
- In other words, remove anything that doesn't make the bug go away.
Copy-friendly signature
Failure Signature
-----------------
If the authentication check fails, the response code from the websocket is `403 Forbidden`, but it should be `401 Unauthorized`.
In other words, remove anything that doesn't make the bug go away.
Error Message
Signature-only (no traceback captured)
Error Message
-------------
If the authentication check fails, the response code from the websocket is `403 Forbidden`, but it should be `401 Unauthorized`.
In other words, remove anything that doesn't make the bug go away.
Minimal Reproduction
import uvicorn
from starlette.applications import Starlette
from starlette.authentication import AuthenticationBackend, AuthenticationError, AuthCredentials, SimpleUser, requires
from starlette.middleware import Middleware
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.websockets import WebSocket
class BasicAuthBackend(AuthenticationBackend):
async def authenticate(self, request):
auth = request.headers.get("Authorization", None)
if auth != 'sample_key':
raise AuthenticationError('Invalid auth credentials')
return AuthCredentials(["authenticated"]), SimpleUser("username")
app = Starlette(
middleware=[
Middleware(AuthenticationMiddleware, backend=BasicAuthBackend()),
],
)
@app.websocket_route("/websocket")
@requires("authenticated", status_code=401)
async def websocket(websocket: WebSocket):
await websocket.accept()
await websocket.send_json({'message': 'Connected and authenticated!'})
await websocket.close()
if __name__ == '__main__':
uvicorn.run("websocket:app", host="0.0.0.0", port=10123)
What Broke
WebSocket connections return 403 Forbidden instead of the expected 401 Unauthorized.
Why It Broke
The WebSocket authentication decorator does not properly handle unauthorized status codes
Fix Options (Details)
Option A — Upgrade to fixed release Safe default (recommended)
Upgrade to version 0.20.1 or later.
Use when you can deploy the upstream fix. It is usually lower-risk than long-lived workarounds.
Fix reference: https://github.com/kludex/starlette/pull/1636
First fixed release: 0.20.1
Last verified: 2026-02-09. Validate in your environment.
When NOT to Use This Fix
- This fix is not applicable if the application requires custom WebSocket status codes.
Verify Fix
Re-run the minimal reproduction on your broken version, then apply the fix and re-run.
Did This Fix Work in Your Case?
Quick signal helps us prioritize which fixes to verify and improve.
Prevention
- Add a TLS smoke test that performs a real handshake in CI (include CA bundle validation and hostname checks).
- Alert on handshake failures by error string and endpoint to catch cert/CA changes quickly.
Version Compatibility Table
| Version | Status |
|---|---|
| 0.20.1 | Fixed |
Related Issues
No related fixes found.
Sources
We don’t republish the full GitHub discussion text. Use the links above for context.