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's really being asked
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.
The full answer
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.
The mistakes people make
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.
What usually comes next
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.
A 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.
Interview question
When authenticating a browser-initiated FastAPI WebSocket connection, which approach correctly handles validation while keeping auth logic reusable?
- a.Pass the JWT via query parameter or cookie during the handshake, validate it in a dependency injected with Depends, and reject with HTTP 403 or close code 1008 if invalid.Correct
- b.Attach the JWT to the Authorization header from the browser client and read it via websocket.headers in the endpoint.
- c.Store a global mapping of connection IDs to users and look up the identity on each incoming message instead of validating per connection.
- d.Have the client send the JWT in the first message after the handshake, then validate it inside the message loop before processing subsequent frames.
Why? this is the answer
Passing the token during the handshake and validating it through an injected dependency allows early rejection and reuses existing HTTP auth logic. Having the client authenticate after the handshake leaves the socket unauthenticated at birth and forces the server to buffer messages until identity is proven.
Just read this? Test yourself on what you have been reading.
Read the original → fastapi.tiangolo.com
- #fastapi
- #websockets
- #authentication
- #security
- #python
Put your scrolling time to good use
Learn one idea, try a quiz and save useful cards for revision. Tezvyn makes it easy to learn and stay current in your tech field, a few minutes at a time.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.
See open roles