Real-time Chat Application with WebSocket, FastAPI and Token Authentication

Build a real-time chat app with FastAPI, WebSocket, and JWT token authentication for secure, asynchronous communication and user management.

Brief Introduction

Real-time Chat Application with WebSocket, FastAPI and Token Authentication (python)
DESCRIPTION:
This example shows how to create a real-time chat application using FastAPI and WebSocket, with JWT token authentication. The server handles multiple connections, secure authentication, and broadcasts messages to all connected users.

ADDITIONAL NOTES:
The application is ready to run in a Python 3.8+ environment with the indicated libraries. It is a robust example including authentication, user management, and real-time communication. For production use, it is recommended to add HTTPS, more detailed error handling, and data persistence.

EXPLANATIONS:
- The create_access_token function generates a JWT token signed with a secret key and expiration.
- The /token endpoint accepts username and password, verifies credentials, and returns a JWT token.
- The /ws WebSocket requires the JWT token as a query parameter to authenticate the user.
- If the token is valid, the user is added to the list of active connections.
- When a message is received from a client, it is sent to all other connected clients (broadcast).
- Connection management is asynchronous, leveraging FastAPI and asyncio features.
- The code includes detailed comments in Italian to facilitate understanding and maintenance.

Example Code: python

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.")
×
×
×
Do you want to regenerate the answer?
×
Export chat
Choose export format
Generazione PDF in corso…
Allegati
×
You are about to close the chat and switch to the image generator. If you are not logged in, you will lose our chat. Do you confirm?
You are viewing a shared chat in temporary mode. It will not be saved.
×
Saved prompts
×
Private note
×
Label
×
Search all chats
×
Your insights
Analyzing…
×
AI Preferences
Assistant name 30
Answer length
AI model
Structured answers
Include examples
Use emojis
Guide me, don't solve Hints and questions instead of a ready answer
More settings →
×
Share this chat
Anyone opening this link can view the chat or add it to their profile as their own chat.
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
Shared chat
Someone shared a chat with you. Do you want to just view it or add it to your chats?
Note: the chat attachments will be shared too. Anyone who adds it will receive a copy of the files in their own folder.
×

Saved messages

Loading...

×

Chat History

example-programs · CHAT HISTORY

Loading...

AI Preferences

×
  • BasicQuick and essential answers for study
  • MediumHigher quality for study and programming
  • AdvancedComplex reasoning and detailed analysis
Explain Steps

What do you need?

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).

Similar Topics

Basic calculator with addition and subtraction
A simple Python calculator for addition and subtraction with an intuitive text interface, ideal for beginners and handling invalid inputs gracefully.
Counting from 1 to 1 with a while loop
Learn how to count from 1 to 1 using a simple Python while loop with clear explanations and no external dependencies required.
Printing the 5 Times Table
This Python program prints the 5 times table from 1 to 1 using a simple for loop and f-string formatting in a standard Python 3 environment.
Program that repeats a message N times
Python program that repeats a user message N times with input validation for positive integers, demonstrating loops and basic input output in Python 3.
Arrival time calculation given departure time and duration in minutes
Python script to calculate arrival time from departure time and duration in minutes with 24h format input and next day handling.
Conversion from Euro to Dollar with Fixed Exchange Rate
Simple Python script to convert euros to dollars using a fixed exchange rate with user input and clear output for easy currency conversion.
Average speed calculation given distance and time
A simple Python script to calculate average speed by taking distance in meters and time in seconds as input and displaying speed in meters per second.
Calculation of time needed to read a book given number of pages and pages/hour
Python script calculates reading time for a book based on total pages and reading speed in pages per hour, showing results in hours and minutes.