Consider a FastAPI WebSocket endpoint that accepts connections without checking any authentication token. What is the likely behavior when a client connects?
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket('/ws') async def websocket_endpoint(websocket: WebSocket): await websocket.accept() await websocket.send_text('Connected') await websocket.close()
Think about what happens if no authentication check is done before accepting the connection.
If the server accepts the WebSocket connection without checking authentication, the client connects successfully and can receive messages. No error occurs because no authentication logic is implemented.
Given a WebSocket connection, which code correctly retrieves the 'Authorization' header token from the connection headers?
async def websocket_endpoint(websocket: WebSocket): # Extract token here pass
Headers are accessed differently than query parameters or cookies.
WebSocket headers can be accessed via websocket.headers, which is a case-insensitive dictionary-like object. The 'Authorization' token is typically sent in headers.
Consider this FastAPI WebSocket endpoint that checks a token and closes the connection if invalid. What does the client receive?
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI() @app.websocket('/ws') async def websocket_endpoint(websocket: WebSocket): token = websocket.headers.get('Authorization') if token != 'validtoken': await websocket.close(code=1008) return await websocket.accept() await websocket.send_text('Welcome!')
What happens if await websocket.close() is called before accept()?
Calling await websocket.close() before accepting closes the connection immediately. The client gets a close frame with code 1008 (policy violation) and no messages.
Examine the code below. It raises RuntimeError: Cannot send data before WebSocket is accepted. What is the cause?
from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket('/ws') async def websocket_endpoint(websocket: WebSocket): token = websocket.headers.get('Authorization') if token == 'validtoken': await websocket.send_text('Welcome!') else: await websocket.close()
Check the order of accept() and send_text() calls.
FastAPI requires calling await websocket.accept() before sending or receiving data. Sending data before accepting causes a RuntimeError.
For a FastAPI app using WebSockets, which approach provides the most secure and scalable authentication method?
Consider security, scalability, and standard practices for real-time authentication.
Sending a JWT token in headers and verifying it before accepting the connection ensures only authorized clients connect. This is secure and scalable for real-time apps.