Skip to content

akashdip2001/Token-Based-Authentication

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 

Repository files navigation

Token-Based-Authentication

Token-Based Authentication in FastAPI


πŸ”‘ Token-Based Authentication in FastAPI (Minimal Example)

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

πŸ–₯️ How to Use

For HTTP route:

# 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

For WebSocket:

// 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);

πŸ’‘ Key Idea

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





⭐ Project 01 click ⭐




About

Token-Based Authentication in FastAPI

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published