📖 Scenario: You are building a chat application where users connect through WebSocket. To keep the chat secure, you want to check if users are authenticated before allowing them to join the chat.
🎯 Goal: Build a FastAPI WebSocket endpoint that authenticates users by checking a token before accepting the connection.
📋 What You'll Learn
Create a dictionary called valid_tokens with exact token-user pairs
Create a variable called auth_token to hold the token from the WebSocket query
Use a for loop with variables token and user to check if auth_token is valid
Accept the WebSocket connection only if the token is valid, otherwise close it
💡 Why This Matters
🌍 Real World
WebSocket authentication is essential for real-time apps like chat, live notifications, or games to ensure only authorized users connect.
💼 Career
Understanding WebSocket authentication is important for backend developers working with real-time communication and security.
Progress0 / 4 steps
1
Create valid tokens dictionary
Create a dictionary called valid_tokens with these exact entries: 'token123': 'alice', 'token456': 'bob', 'token789': 'carol'.
FastAPI
Hint
Use curly braces {} to create the dictionary with the exact keys and values.
2
Extract token from WebSocket query
Inside the websocket_endpoint function, create a variable called auth_token that gets the token from websocket.query_params.get('token').
FastAPI
Hint
Use websocket.query_params.get('token') to get the token from the URL query.
3
Check if token is valid
Use a for loop with variables token and user to iterate over valid_tokens.items(). Inside the loop, check if auth_token == token. If yes, accept the WebSocket connection with await websocket.accept() and break the loop.
FastAPI
Hint
Use for token, user in valid_tokens.items(): to loop through tokens and users.
4
Close connection if token invalid
After the for loop, add an else clause that closes the WebSocket connection with await websocket.close() if no valid token was found.
FastAPI
Hint
Use the else clause on the for loop to close the connection if no token matches.
Practice
(1/5)
1. What is the main purpose of WebSocket authentication in FastAPI?
easy
A. To speed up the WebSocket connection process
B. To confirm the user's identity before allowing the WebSocket connection
C. To encrypt the WebSocket messages automatically
D. To log all WebSocket messages for debugging
Solution
Step 1: Understand WebSocket authentication role
Authentication ensures only authorized users can connect to the WebSocket.
Step 2: Identify the main goal in FastAPI context
FastAPI uses authentication to confirm user identity before opening the connection.
Final Answer:
To confirm the user's identity before allowing the WebSocket connection -> Option B
Quick Check:
Authentication = Confirm identity [OK]
Hint: Authentication means confirming user identity before connection [OK]
Common Mistakes:
Confusing authentication with encryption
Thinking authentication speeds up connection
Assuming authentication logs messages
2. Which of the following is the correct way to accept a WebSocket connection with token authentication in FastAPI?
easy
A. await websocket.accept() without checking token
B. Call await websocket.close() before checking token
C. Use await websocket.send_text() before accepting
D. Check token, then call await websocket.accept() if valid
Solution
Step 1: Understand WebSocket connection flow
You must check the token first to decide if connection is allowed.
Step 2: Accept connection only if token is valid
Call await websocket.accept() only after confirming token validity.
Final Answer:
Check token, then call await websocket.accept() if valid -> Option D
Quick Check:
Accept after token check = C [OK]
Hint: Accept connection only after validating token [OK]
Common Mistakes:
Accepting connection before token check
Closing connection before checking token
Sending messages before accepting connection
3. Given this FastAPI WebSocket code snippet, what will happen if the token is invalid?
C. Accepting connection before sending 'Unauthorized' message
D. Missing await before websocket.close()
Solution
Step 1: Analyze connection flow on invalid token
The code calls await websocket.accept() before sending 'Unauthorized' and closing.
Step 2: Understand best practice for unauthorized access
It is better to close connection immediately without accepting it to avoid opening unauthorized connection.
Final Answer:
Accepting connection before sending 'Unauthorized' message -> Option C
Quick Check:
Unauthorized should close without accept [OK]
Hint: Do not accept connection before rejecting unauthorized users [OK]
Common Mistakes:
Accepting connection before rejecting
Ignoring connection close on invalid token
Confusing headers and query parameters
5. You want to authenticate WebSocket connections in FastAPI using a token passed as a query parameter. Which approach correctly handles authentication and rejects unauthorized users cleanly?
hard
A. Check token from query params; if invalid, call await websocket.close(1008) before accept; else accept connection
B. Accept connection first, then check token; if invalid, send 'Unauthorized' message and close
C. Ignore token and accept all connections; handle authorization in message handlers
D. Check token in headers only; ignore query parameters
Solution
Step 1: Understand token location and validation
Token is passed as query parameter, so check websocket.query_params for token.
Step 2: Handle unauthorized users before accepting connection
If token is invalid, close connection immediately with code 1008 to reject cleanly.
Step 3: Accept connection only if token is valid
Only call await websocket.accept() after confirming token validity.
Final Answer:
Check token from query params; if invalid, call await websocket.close(1008) before accept; else accept connection -> Option A
Quick Check:
Reject before accept with close(1008) = A [OK]
Hint: Reject unauthorized before accept using close(1008) [OK]
Common Mistakes:
Accepting connection before token check
Ignoring query parameters for token
Handling authorization after connection open
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.