Build a real-time chat app with FastAPI, WebSocket, and JWT token authentication for secure, asynchronous communication and user management.
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
from typing import List, Dict
from datetime import datetime, timedelta
import asyncio
# --- CONFIGURATION AND CONSTANTS ---
SECRET_KEY = "a1b2c3d4e5f6g7h8i9j0" # Secret key to sign JWT tokens
ALGORITHM = "HS256" # JWT signing algorithm
ACCESS_TOKEN_EXPIRE_MINUTES = 30 # Token validity duration in minutes
# --- DATA MODELS ---
class User(BaseModel):
username: str
hashed_password: str
class UserInDB(User):
pass
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: str = None
# --- SIMULATED DATABASE ---
# In a real app use a real database
fake_users_db = {
"alice": {
"username": "alice",
"hashed_password": "$2b$12$KIXQJ0Q1yZfQ9q9kq6V3Uu0Q8j5Q7pQ5NqYq1KZ5S9h6mYxM6FZ7e" # password: secret123
},
"bob": {
"username": "bob",
"hashed_password": "$2b$12$7Q7Q7Q7Q7Q7Q7Q7Q7Q7Q7OqQ7Q7Q7Q7Q7Q7Q7Q7Q7Q7Q7Q7Q7Q7Q7" # password: password
}
}
# --- PASSWORD UTILITIES ---
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def verify_password(plain_password, hashed_password):
# Verify that the plain password matches the hash
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
# Generate secure hash for the password
return pwd_context.hash(password)
# --- USER UTILITIES ---
def get_user(db, username: str):
# Retrieve user from simulated db
if username in db:
user_dict = db[username]
return UserInDB(**user_dict)
return None
def authenticate_user(db, username: str, password: str):
# Authenticate user by verifying password
user = get_user(db, username)
if not user:
return False
if not verify_password(password, user.hashed_password):
return False
return user
# --- JWT TOKEN CREATION ---
def create_access_token(data: dict, expires_delta: timedelta = None):
# Create a JWT token with payload and expiration
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
# --- FASTAPI APP ---
app = FastAPI()
# --- WEBSOCKET CONNECTION MANAGEMENT ---
class ConnectionManager:
def __init__(self):
self.active_connections: Dict[str, WebSocket] = {}
self.lock = asyncio.Lock() # To avoid race conditions
async def connect(self, username: str, websocket: WebSocket):
# Accept connection and register it
await websocket.accept()
async with self.lock:
self.active_connections[username] = websocket
async def disconnect(self, username: str):
# Remove connection
async with self.lock:
if username in self.active_connections:
del self.active_connections[username]
async def send_personal_message(self, message: str, websocket: WebSocket):
# Send message to single client
await websocket.send_text(message)
async def broadcast(self, message: str):
# Send message to all connected clients
async with self.lock:
for connection in self.active_connections.values():
await connection.send_text(message)
manager = ConnectionManager()
# --- TOKEN DEPENDENCY ---
async def get_current_user(token: str):
# Decode and verify JWT token
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
token_data = TokenData(username=username)
except JWTError:
raise credentials_exception
user = get_user(fake_users_db, username=token_data.username)
if user is None:
raise credentials_exception
return user
# --- LOGIN AND TOKEN ENDPOINT ---
@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
# Endpoint to obtain JWT token
user = authenticate_user(fake_users_db, form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": user.username}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
# --- WEBSOCKET CHAT ENDPOINT ---
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
# Extract token from query params
token = websocket.query_params.get("token")
if token is None:
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
return
try:
user = await get_current_user(token)
except HTTPException:
await websocket.close(code=status.WS_1008_POLICY_VIOLATION)
return
username = user.username
await manager.connect(username, websocket)
try:
await manager.broadcast(f"{username} has connected to the chat.")
while True:
data = await websocket.receive_text()
# Broadcast received message to all
await manager.broadcast(f"{username}: {data}")
except WebSocketDisconnect:
await manager.disconnect(username)
await manager.broadcast(f"{username} has disconnected from the chat.")FastAPI: asynchronous web framework for Python, handles HTTP and WebSocket.
uvicorn: ASGI server to run FastAPI.
python-jose: library for managing and verifying JWT (JSON Web Token).
passlib[bcrypt]: library for secure password hashing.
pydantic: for data validation and serialization.
WebSocket: protocol for real-time bidirectional communications.
Software dependencies: fastapi, uvicorn, python-jose, passlib[bcrypt], pydantic.
FastAPI configuration: HTTP endpoint for login and WebSocket for chat.
Authentication: /token endpoint to obtain JWT via username and password.
Security middleware: verifies JWT token for WebSocket connections.
Connected users management: in-memory data structure to track active connections.
Message broadcast: sending received messages to all connected users.
Server configuration: uvicorn main:app --reload for development.
WebSocket client configuration: Authorization header with Bearer token for authentication.
Arduino wiring/pinout example not applicable (pure software).