0
0
FastAPIframework~20 mins

WebSocket authentication in FastAPI - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
WebSocket Authentication Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when a WebSocket connection is accepted without authentication?

Consider a FastAPI WebSocket endpoint that accepts connections without checking any authentication token. What is the likely behavior when a client connects?

FastAPI
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()
AThe server rejects the connection with a 401 Unauthorized error.
BThe server raises a runtime error due to missing authentication.
CThe connection hangs indefinitely without response.
DThe client connects successfully and receives the 'Connected' message.
Attempts:
2 left
💡 Hint

Think about what happens if no authentication check is done before accepting the connection.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly extracts a token from WebSocket headers in FastAPI?

Given a WebSocket connection, which code correctly retrieves the 'Authorization' header token from the connection headers?

FastAPI
async def websocket_endpoint(websocket: WebSocket):
    # Extract token here
    pass
Atoken = websocket.cookies.get('Authorization')
Btoken = websocket.query_params['Authorization']
Ctoken = websocket.headers.get('Authorization')
Dtoken = websocket.body['Authorization']
Attempts:
2 left
💡 Hint

Headers are accessed differently than query parameters or cookies.

state_output
advanced
2:00remaining
What is the output when a WebSocket connection is closed after failed authentication?

Consider this FastAPI WebSocket endpoint that checks a token and closes the connection if invalid. What does the client receive?

FastAPI
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!')
AThe client connection closes immediately with close code 1008 and no message.
BThe client receives 'Welcome!' message before connection closes.
CThe server raises a WebSocketDisconnect exception.
DThe client connection stays open but receives no messages.
Attempts:
2 left
💡 Hint

What happens if await websocket.close() is called before accept()?

🔧 Debug
advanced
2:00remaining
Why does this FastAPI WebSocket authentication code raise a RuntimeError?

Examine the code below. It raises RuntimeError: Cannot send data before WebSocket is accepted. What is the cause?

FastAPI
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()
AThe WebSocket connection was not accepted before sending messages.
BThe token variable is None causing a TypeError.
CThe headers attribute is not accessible in WebSocket.
DThe close() method is called without a close code.
Attempts:
2 left
💡 Hint

Check the order of accept() and send_text() calls.

🧠 Conceptual
expert
3:00remaining
Which approach best secures WebSocket authentication in FastAPI for real-time apps?

For a FastAPI app using WebSockets, which approach provides the most secure and scalable authentication method?

AAuthenticate users via cookies only and accept all WebSocket connections without checks.
BSend a JWT token in the WebSocket headers and verify it on connection before accepting.
CAccept all WebSocket connections and send authentication requests as messages after connection.
DUse IP address filtering to allow only trusted clients to connect.
Attempts:
2 left
💡 Hint

Consider security, scalability, and standard practices for real-time authentication.