tezvyn:

How do you authenticate a FastAPI WebSocket connection?

AI-drafted, machine-checkedSource: fastapi.tiangolo.comintermediate
How do you authenticate a FastAPI WebSocket connection?

This tests WebSocket limits and FastAPI dependency injection. Pass the JWT via query parameter or cookie at handshake, validate it with Depends, and reject with HTTP 403 or 1008 close.

WHAT THIS TESTS: This tests whether you know that FastAPI WebSocket endpoints can use Depends and other dependencies, and whether you understand the HTTP upgrade handshake constraints that prevent standard Bearer headers in browser clients. The interviewer wants to see if you can adapt token-based security to a persistent connection model rather than treating it like a stateless HTTP request.

A GOOD ANSWER COVERS: First, state that the WebSocket handshake is an HTTP request, but browser JavaScript APIs do not allow custom headers, so you must pass credentials via query parameters or cookies. Second, explain that FastAPI lets you inject dependencies into WebSocket endpoints with Depends, meaning you can reuse JWT or OAuth2 validation logic that you already use for HTTP routes. Third, describe reading the token from websocket.query_params or websocket.cookies inside a dependency, verifying it with your existing auth backend, and returning the user to the endpoint. Fourth, note that you should reject unauthenticated clients early with an HTTP 403 before the upgrade completes, or close the connection with a 1008 policy violation code if discovered after. Fifth, mention that FastAPI provides WebSocketException for this purpose and that you should close cleanly rather than leaving dangling connections.

COMMON WRONG ANSWERS: A major red flag is suggesting the client sends an auth message after the handshake and the server processes it later. This leaves the socket unauthenticated at birth and forces you to buffer messages until identity is proven. Another mistake is claiming you can simply attach an Authorization header from a browser without noting the JavaScript API limitation. A third anti-pattern is storing a global mapping of connection IDs to users instead of validating per connection, which breaks horizontally across multiple workers.

LIKELY FOLLOW-UPS: Expect questions about token refresh over a long-lived socket, how to force-disconnect a user on logout across multiple servers, or how to mitigate CSRF when using cookies. The interviewer may also ask how you would test this with FastAPI's TestClient and whether you can reuse existing HTTP security dependencies verbatim or if you need a thin wrapper. They might also ask about scaling connection state in a multi-node deployment.

ONE CONCRETE EXAMPLE: You create an async dependency get_ws_user that accepts websocket: WebSocket, extracts token = websocket.query_params.get("token"), validates the JWT against your auth backend, and returns a User. In the endpoint decorated with app.websocket("/ws"), you write async def websocket_endpoint(websocket: WebSocket, user: User = Depends(get_ws_user)). If validation fails, you call await websocket.close(code=1008) or raise WebSocketException before entering the message loop. This keeps the auth logic decoupled and reusable.

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.