Token-Based Authentication in FastAPI
from fastapi import FastAPI, Request, HTTPException, WebSocket
app = FastAPI()
# π Define a secret token (could also load from environment variable)
SECRET_TOKEN = "my-super-secret-token"
# -------------------------
# 1. Token auth for normal HTTP route
# -------------------------
@app.get("/secure-data")
async def secure_data(request: Request):
token = request.headers.get("X-Auth-Token") # client must send in header
if token != SECRET_TOKEN:
raise HTTPException(status_code=401, detail="Invalid or missing token")
return {"message": "β
Access granted", "data": "Here is your secret data!"}
# -------------------------
# 2. Token auth for WebSocket connection
# -------------------------
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
# token comes as query param: ws://localhost:8000/ws?token=xxx
token = websocket.query_params.get("token")
if token != SECRET_TOKEN:
await websocket.close(code=4401) # custom code for unauthorized
return
await websocket.accept()
await websocket.send_text("β
WebSocket connected with valid token")
# from here, keep sending/receiving data
# works
curl -H "X-Auth-Token: my-super-secret-token" http://127.0.0.1:8000/secure-data
# fails
curl http://127.0.0.1:8000/secure-data
// client-side JS
const ws = new WebSocket("ws://127.0.0.1:8000/ws?token=my-super-secret-token");
ws.onmessage = (msg) => console.log(msg.data);
-
Token is like a shared secret between client & server.
-
The server checks every incoming request:
- If token matches β allow access.
- If token missing or wrong β deny with 401 (HTTP) or close connection (WebSocket).
-
Unlike username/password login, this is lightweight and perfect for LAN devices.