skip to content

A FastAPI team reuses its get_current_user dependency, built on OAuth2PasswordBearer, on an @app.websocket endpoint, and every connection fails with a TypeError. Why, and how should the socket authenticate?

level: seniorimportance: must knowfreq 35%

answer

  1. what the security classes ask FastAPI to inject
  2. a WebSocket is not a Request
  3. browsers cannot add an Authorization header
  4. a socket-aware dependency raising a close code

basics

~20 s

The fastapi.security classes take request: Request, which FastAPI injects only on HTTP routes, so on a WebSocket the argument is missing. Use a socket dependency that reads a Query, Cookie or Header value, verifies it, and raises WebSocketException.

solid answer

~40 s

`OAuth2PasswordBearer`, `HTTPBearer`, `APIKeyHeader` and the other `fastapi.security` classes are dependencies whose `__call__` takes `request: Request`. FastAPI fills a `Request`-annotated parameter only for HTTP requests; on a WebSocket route it fills `WebSocket` parameters instead, so the call fails with `TypeError: OAuth2PasswordBearer.__call__() missing 1 required positional argument: 'request'`. The fix is a socket-specific dependency: read the credential from a `Query`, `Cookie` or `Header` parameter, verify it with the same token function the HTTP `get_current_user` uses, and raise `WebSocketException(code=status.WS_1008_POLICY_VIOLATION)` on failure. The client decides the source: a browser's WebSocket API cannot add an `Authorization` header, so browser clients send a cookie or a short-lived token in the query string, while other clients can use `Header`. A dependency annotated with Starlette's `HTTPConnection` can serve both kinds of route.

code

python · 30 lines
python
from typing import Annotated

from fastapi import Cookie, Depends, FastAPI, Query, WebSocket, WebSocketException, status

app = FastAPI()
SESSIONS = {"t-alice": "alice"}


def user_from_token(token: str | None) -> str | None:
    # Shared with the HTTP get_current_user; real code verifies a signed token here.
    return SESSIONS.get(token or "")


async def get_socket_user(
    token: Annotated[str | None, Query()] = None,
    session: Annotated[str | None, Cookie()] = None,
) -> str:
    user = user_from_token(token or session)
    if user is None:
        raise WebSocketException(code=status.WS_1008_POLICY_VIOLATION)
    return user


SocketUser = Annotated[str, Depends(get_socket_user)]


@app.websocket("/rooms/{room_id}/ws")
async def room_socket(websocket: WebSocket, room_id: str, user: SocketUser):
    await websocket.accept()
    await websocket.send_json({"room": room_id, "user": user})

go deeper

for a junior

Know that a WebSocket route authenticates through a dependency that reads a query parameter, cookie or header and raises WebSocketException when the check fails.

for a middle

Explain why the fastapi.security classes fail on sockets: their call needs a Request, and FastAPI injects a WebSocket there instead.

for a senior

Structure it for production: one shared token check, a socket dependency per transport, refusal before accept, expiry re-checked on long connections, and per-room authorisation.

for a principal

Decide whether socket authentication lives in the app or at a gateway in front of it, and keep the token rules identical across HTTP and WebSocket routes either way.

Teams that already protect HTTP routes with `Depends(get_current_user)` naturally try the same alias on their chat socket. It fails on the first connection, and the reason is in how FastAPI injects connection objects. ## Why the HTTP dependency breaks 1. `get_current_user` depends on `oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")`. 2. The classes in `fastapi.security`, including `OAuth2PasswordBearer`, `HTTPBearer`, `HTTPBasic`, `APIKeyHeader`, `APIKeyQuery`, `APIKeyCookie` and `OpenIdConnect`, are callables whose `__call__` declares **`request: Request`**. 3. FastAPI injects a `Request`-annotated parameter only when the connection is an HTTP request. On a WebSocket route it injects parameters annotated `WebSocket`, and parameters annotated Starlette's `HTTPConnection`, the base class of both. 4. The `request` argument is therefore left out, and the call fails with `TypeError: OAuth2PasswordBearer.__call__() missing 1 required positional argument: 'request'`. Nothing about the token is wrong; the security class never gets as far as reading it. ## Where a socket's credential can come from | Source | FastAPI parameter | Browser client | Other clients | Watch out for | |---|---|---|---|---| | query string | `Annotated[str \| None, Query()]` | yes | yes | URLs land in access and proxy logs, so use short-lived tokens | | cookie | `Annotated[str \| None, Cookie()]` | yes, sent automatically | if they keep cookies | cross-site pages can trigger the upgrade, so the Origin must be checked | | `Authorization` header | `Annotated[str \| None, Header()]` | no | yes | browsers' WebSocket API cannot set it | | first message after `accept()` | none; read in the handler | yes | yes | the socket is accepted before anyone is authenticated | Why browsers cannot set the header, and the trade-offs between these transports, are covered with WebSocket authentication; the FastAPI question is how to wire whichever one you choose. ## A socket-aware dependency The clean structure splits verification from transport: - Move the token check (signature, expiry, user lookup) into a plain function both dependencies call. - Keep `get_current_user` for HTTP routes, built on the security class. - Add `get_socket_user`, which declares `token: Annotated[str | None, Query()] = None` and `session: Annotated[str | None, Cookie()] = None`, calls the shared check, and raises `WebSocketException(code=status.WS_1008_POLICY_VIOLATION)` on failure. - Publish an alias such as `SocketUser = Annotated[str, Depends(get_socket_user)]` so every socket route authenticates the same way. Because the dependency runs before the handler, a failure happens before `accept()`. Under Uvicorn the client sees a refused handshake (HTTP 403); in-process tests see `WebSocketDisconnect` with code 1008. A single dependency can serve both route types if it takes `conn: HTTPConnection` and reads `conn.headers`, `conn.cookies` or `conn.query_params`. It must still raise the right exception for the route: `HTTPException` on HTTP, `WebSocketException` on a socket. ## A ticket endpoint for browser clients Putting the long-lived access token in the socket URL is the weakest of the browser options, because URLs are logged by servers and proxies. A common FastAPI wiring keeps the strong token on the HTTP side: 1. The page calls an ordinary HTTP endpoint, protected by the existing `get_current_user`, that issues a one-time ticket valid for a few seconds. 2. The page opens the socket with `?ticket=...` in the URL. 3. The socket dependency reads it with `Query()`, verifies it and marks it used, then returns the user. A leaked ticket is worthless moments later, and the HTTP security classes keep doing the work they were built for. ## What still differs from HTTP authentication - **Resolved once.** Dependencies run when the connection opens and never again for later messages, so a token that expires mid-connection keeps working unless the handler checks expiry itself. - **Authorisation per action.** Joining a room or posting to it should be checked in the handler for each request, not only at connect. - **No docs integration.** The docs UI's Authorize button does nothing for sockets, since WebSocket routes are not in the OpenAPI schema. - **No `HTTPException`.** The dependency raises `WebSocketException`; an `HTTPException` behaves inconsistently on sockets. ## Review checklist 1. Socket routes use a socket-specific dependency or one typed with `HTTPConnection`, never a `fastapi.security` class. 2. The token check is shared with HTTP authentication, not duplicated. 3. Query-string tokens are short-lived and kept out of logs where possible. 4. Cookie-authenticated sockets check the `Origin` header. 5. Long-lived connections re-check expiry or are closed when the credential lapses.

  • Can one FastAPI dependency authenticate both HTTP and WebSocket routes?
    Yes, if it does not go through the `fastapi.security` classes. Annotate its connection parameter as Starlette's `HTTPConnection`, the common base of `Request` and `WebSocket`, and FastAPI injects whichever the route has; read `conn.headers`, `conn.cookies` or `conn.query_params`. The failure still differs per route type: raise `HTTPException` when `conn.scope["type"]` is `"http"` and `WebSocketException` when it is `"websocket"`.
  • The socket authenticated at connect; what does FastAPI do when that token expires an hour later?
    Nothing. FastAPI resolves a WebSocket route's dependencies once, when the connection opens, and never re-runs them for later messages, so the user value stays whatever it was at connect. If expiry matters, keep the expiry time from the token and have the handler raise `WebSocketException(code=status.WS_1008_POLICY_VIOLATION)` once it passes. The protocol-side options for re-authenticating are covered with WebSocket authentication.
  • Why not accept the socket and read the token from the first message instead?
    It keeps the token out of URLs, which is its appeal, but in FastAPI it moves authentication out of the dependency system. The handler must `accept()` an anonymous connection, wait a bounded time for one message, verify it and only then join a room. Every unauthenticated client holds an accepted socket until that deadline, and every socket route must repeat the pattern correctly.

  • OAuth2PasswordBearer works on WebSocket routes exactly as it does on HTTP routes.
  • A browser can put a bearer token in the Authorization header of the WebSocket upgrade.
  • A failed socket dependency should raise HTTPException(status_code=401).
  • Dependencies run again for every message, so token expiry is enforced automatically.
  • A token in the query string is as private as one in a header.