4. Authentication, Security & Configuration

Configuration, .env Secrets, CORS & API Security Basics

Keep API keys and database URLs out of Git using .env and pydantic-settings, configure CORS safely for frontends, and apply essential backend security practices.

5 min readUpdated 2026-11-30
In This Lesson
  • Externalize secrets and environment config cleanly using .env and typed Settings
  • Understand why browsers enforce CORS and how to whitelist exact frontend origins
  • Apply essential API hygiene: fail-fast config, minimal error leaks, and safe defaults

Moving an API from your laptop to production means changing database URLs, disabling debug reload, and keeping JWT signing secrets completely out of source code.

1. Architecture: Startup Config & Middleware Outer Shell

Security and configuration guard the outermost ring of your backend lifecycle:

text
App Boot:  OS Env / .env ─▶ Settings(BaseSettings) ─▶ Fail fast if JWT_SECRET missing!
                                 │
Request:   Browser fetch() ─▶ CORSMiddleware (handles OPTIONS preflight + Origin check)
                                 │
                                 ▼
                           Auth Guard ─▶ Pydantic ─▶ Route Handler

Because Settings() runs at boot and CORSMiddleware wraps every route, bad configuration fails immediately on deploy and unauthorized cross-origin browser requests are blocked before touching business logic.

2. Environment Variables & pydantic-settings

Rule #1 of backend engineering: Never hardcode passwords, API keys, or JWT secrets inside .py files or commit .env to Git!

Follow the 12-Factor App pattern:

  • Store local secrets in .env (listed in .gitignore).
  • Commit a .env.example file with safe placeholder keys so teammates and CI know every required variable.
  • In production (Render, Fly.io, Cloud Run, AWS), inject secrets directly as environment variables or via a secret manager—no .env file needed on the server!
text
# .env.example (committed to Git)          # .env (local only, in .gitignore!)
DATABASE_URL=sqlite:///./app.db            DATABASE_URL=sqlite:///./app.db
JWT_SECRET=replace-with-32-char-secret     JWT_SECRET=9f8e7d6c5b4a3210fedcba9876543210
ALLOWED_ORIGINS=["http://localhost:3000"]  ALLOWED_ORIGINS=["https://yadavacademy.org"]
DEBUG=false                                DEBUG=true
python
# config.py
from pydantic import Field
from pydantic_settings import BaseSettings, SettingsConfigDict

class Settings(BaseSettings):
    database_url: str = "sqlite:///./app.db"
    jwt_secret: str = Field(min_length=32)
    allowed_origins: list[str] = ["http://localhost:3000"]
    debug: bool = False

    model_config = SettingsConfigDict(env_file=".env", extra="ignore")

settings = Settings()  # Crashes immediately on boot if JWT_SECRET is missing or short!

Failing fast at startup when JWT_SECRET is missing is much safer than silently falling back to "dev-secret" and running production with a guessable key.

If You Accidentally Commit .env, Deleting It Isn't Enough

Git remembers every commit in history. If a secret ever hits GitHub—even in a single commit that you immediately revert—assume it is compromised, rotate/revoke the API key or secret immediately, and purge it from Git history.

3. Understanding CORS & Browser Preflight (OPTIONS)

Suppose your Next.js frontend runs on https://yadavacademy.org and calls your Python API on https://api.yadavacademy.org. Because the scheme, host, or port differs, browsers enforce the Same-Origin Policy and block JavaScript from reading responses unless your backend sends explicit CORS headers.

Note a key distinction: CORS is enforced by web browsers, NOT by curl, Postman, or Python httpx! (That's why CORS is not a substitute for Bearer token authentication—an attacker can still call your API directly from a terminal.)

For requests carrying Authorization headers or PATCH/DELETE methods, the browser sends a preflight OPTIONS request first:

Browser CORS Preflight (OPTIONS) Handshake
Frontend (:3000)

OPTIONS + Origin header

CORSMiddleware

Origin in allowlist?

200 + Actual POST

Access-Control-Allow-Origin

Browsers send an automatic OPTIONS preflight before cross-origin POST/PATCH/Authorization calls to verify allowed origins.

python
from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.allowed_origins,  # Exact origins from env config
    allow_credentials=True,
    allow_methods=["GET", "POST", "PATCH", "DELETE"],
    allow_headers=["Authorization", "Content-Type"],
)
Never Pair allow_origins=['*'] with allow_credentials=True

Allowing wildcard * origins alongside allow_credentials=True violates the Fetch/CORS specification (browsers reject the response) and signals overly permissive access. Always whitelist your exact frontend domain(s) from environment config!

4. Essential API Security Hygiene

  • Suppress tracebacks in production (debug=False): Log the full exception server-side (logger.exception(...)) and return a generic 500 Internal Server Error JSON message—never leak SQL queries, file paths, or local variables to clients.
  • Clamp pagination & payload sizes: Enforce Query(ge=1, le=100) on list endpoints so nobody triggers GET /logs?limit=10000000 and exhausts server RAM.
  • Rate limiting: Protect /auth/login, /auth/register, and expensive search routes against brute-force attacks using a reverse proxy (Cloudflare/Nginx) or middleware such as slowapi (e.g. 5/minute per IP on login).
  • HTTP security headers: Return X-Content-Type-Options: nosniff, X-Frame-Options: DENY, and Strict-Transport-Security (HSTS) at your reverse proxy or ASGI middleware.
  • HTTPS everywhere in production: Terminate TLS at your load balancer/proxy so Bearer tokens and passwords are never sent in cleartext over public Wi-Fi.

Try It Yourself in the Playground

Test fail-fast environment configuration validation and origin allowlist checking in pure Python:

Python 3Try It Live: Fail-Fast Config & CORS Origin Check
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Why should a repo include .env.example in Git while keeping .env inside .gitignore?

Quick Checkpoints

Check Your Understanding

Why does a browser block fetch('https://api.example.com/courses') from http://localhost:3000 unless configured?

Check Your Understanding

What is the safest behavior when JWT_SECRET is missing from the server environment at startup?