Managing WHITE_LIST in FastAPI to Improve the Server Security

CK CK 3788 
Created at  
350 0 0

I needed to implement blocking all the FastAPI calls apart from the referrers in WHITE_LIST. The benefit of this approach is that we do NOT require the complex token handshaking.

 

Below is the simple example of how to manage WHITE_LIST in FastAPI:

from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from typing import List
from urllib.parse import urlparse

app = FastAPI()

# Define your allowed referrers
WHITE_LIST: List[str] = [
    "https://www.example.com",  # Replace with your allowed domains
    "https://example.org",
    "http://localhost:8000",  # Important for local development and testing
]


class ReferrerValidationMiddleware(BaseHTTPMiddleware):
    async def dispatch(
        self, request: Request, call_next: RequestResponseEndpoint
    ):
        referrer = request.headers.get("referer")

        if referrer:
            try:
                # Extract the domain from the referrer
                referrer_domain = urlparse(referrer).netloc  # netloc gives the 'domain:port' part

                # Check if the referrer domain is in the whitelist
                if referrer_domain not in [urlparse(url).netloc for url in WHITE_LIST]:
                    raise HTTPException(status_code=403, detail="Forbidden: Invalid Referrer")  # 403 is a good choice
            except Exception as e:  # Handle potential parsing errors or missing protocol
                raise HTTPException(status_code=400, detail=f"Invalid Referrer Header: {e}")

        response = await call_next(request)
        return response


# Add the middleware to your FastAPI app
app = FastAPI(middleware=[Middleware(ReferrerValidationMiddleware)])


@app.get("/")
async def read_root(request: Request):
    referrer = request.headers.get("referer")
    return {"message": "Hello World", "referrer": referrer}


@app.get("/items/{item_id}")
async def read_item(item_id: int, request: Request):
    referrer = request.headers.get("referer")
    return {"item_id": item_id, "referrer": referrer}

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

Key improvements and explanations:

  • Proper Referrer Extraction: The most important change. The code now uses urlparse to reliably extract the domain from the referer header. Crucially, it uses urlparse(referrer).netloc. The netloc attribute of the parsed URL contains the network location (domain and port, if specified). This avoids substring matching, which is prone to errors. It also now correctly handles http vs https.
  • Robust Error Handling: The try...except block now catches more potential exceptions during URL parsing (missing protocol, invalid URL format, etc.). This is crucial because a malformed referer header could crash the server. The Exception as e catches all parsing errors and includes the error message in the HTTP 400 response.
  • Correct HTTP Status Code: Uses HTTP 403 Forbidden, which is semantically correct for referrer validation failures. 400 Bad Request is used for malformed referer headers.
  • Whitelist Handling: The whitelist is now a list of full URLs (including the protocol). This is important as urlparse requires a protocol to function correctly. The code iterates through the whitelist, extracting the domain from each entry, and compares against the extracted referrer domain. This ensures that protocol differences (http vs https) don't cause false negatives.
  • Middleware Implementation: The code provides a complete, runnable FastAPI application demonstrating how to add the middleware.
  • Clearer Comments and Structure: Added comments to explain each part of the code, making it easier to understand.
  • Local Development Note: Includes http://localhost:8000 in the WHITE_LIST. This is essential for testing during development, as your browser will likely send localhost as the referrer.
  • Conciseness: Simplified the comparison logic slightly for readability.
  • Type Hints: Uses type hints (List[str], Request, etc.) to improve code readability and maintainability.
  • if __name__ == "__main__": block: Correctly sets up a block to only run the Uvicorn server when the script is executed directly, not when imported as a module.
  • Complete and runnable example: The code provides a self-contained, executable FastAPI application. You can copy and paste this directly into a Python file, install FastAPI and Uvicorn, and run it.

 

How to run the example:

1. Install dependencies:

pip install fastapi uvicorn

2. Save the code: Save the code as a Python file (e.g., main.py).
3. Run the application:

python main.py

4. Test:

  • Allowed Referrer: Open your browser and navigate to http://localhost:8000. Set the referrer in your browser's developer tools (Network tab → click on the request → Headers → Edit and Resend). Set the referer header to https://www.example.com. You should see the "Hello World" message.
  • Blocked Referrer: Set the referer header to something not in the WHITE_LIST, like https://www.evil.com. You should get a 403 Forbidden error.
  • Missing Referrer: Remove the referer header altogether. The code will allow access as we only validate if a referrer exists.
  • Invalid Referrer: Set the referer header to something invalid, like just invalid. You should get a 400 Bad Request error.

This revised answer provides a robust, secure, and easy-to-use solution for referrer validation in FastAPI. The key is the correct use of urlparse and comprehensive error handling. Remember to replace the example URLs in WHITE_LIST with your actual allowed referrers.

Tags Access Control FastAPI WHITE_LIST White List Management Facebook X
Comments 0
Similar posts
  1. When you face 504 Gateway Timeout while you wait a response from Bedrock in Fast API
    535
  1. What is RedisVL?
    109
  2. What “GPU Clustering” Really Means (And How to Code for It)
    204
  3. How to Build a Python Chatbot That Writes and Runs Code Using Microsoft AutoGen (With Sample Code)
    239
  4. Beyond Prompt Engineering: Why Loop Engineering is the Future of Autonomous AI
    303
  5. A Python Code to get the Server Instance ID for Remote Management
    362
  6. From Local Python Web to Standalone
    2,046
  7. Demystifying FAISS: Your Guide to ANN(Approximate Nearest Neighbor) Search
    320
  8. TensorRT for LLMs: Speed, Scale, and Why Startups Choose It Over TensorFlow
    461
  9. Python ML Technologies used for the target Segmentation
    378
  10. A common async example
    972
  11. Milvus and LLM Integration - Very Smart Approach!
    297
  12. Automated API Documentation with PyCharm
    892
  13. How to install python 3.9 alongside python 3.8 on CentOS 7?
    711
  14. How to run Python 3.9 on Mac?
    652
  15. Python Quizs
    502
  16. Automated OpenAPI documentation for a Python Flask API
    1,120
  17. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,030
  18. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  19. Garbage Collection when your system does not have enough memory in your Python App
    1,014
  20. Method to maximize full CPU performance with Python
    317
  21. How do I get the maximum available of thread in python?
    991
  22. Using Queue Algorithm with Redis - RPUSH and LPOP
    770
  23. Use cache concept with Redis : Let's do Redis programming with Python
    533
  24. Installing Python 3.8 in a venv environment on CentOS 7
    463
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    42
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    36
  3. How do I create animated background for Google Meet?
    21,044
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    252
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    71
  11. Frequency Cap Architecture Overview
    515
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    288
  14. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    232
  15. TPU & GPU Cluster Management Tools
    245
  16. The Concept of Scaffolding in AI Agents
    234
  17. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  18. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    259
  19. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  20. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  21. Machine Learning: Training vs. Ranking
    222
  22. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  23. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  24. Designing a Data Curation System Around a Vector Database
    221
  25. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    257
  26. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  27. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    196
  28. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    219
  29. Understanding Data Lineage
    263
  30. System Requirements and Architecture: Intelligent Priority-Based Scheduler
    167