{"id":25255010,"url":"https://github.com/VolkanSah/Securing-FastAPI-Applications","last_synced_at":"2026-01-19T22:00:57.360Z","repository":{"id":272191365,"uuid":"915784383","full_name":"VolkanSah/Securing-FastAPI-Applications","owner":"VolkanSah","description":"This guide covers key areas of API security, including authentication, input validation, HTTPS, and more. Each section includes examples and tools to help you apply best practices in real-world applications.","archived":false,"fork":false,"pushed_at":"2025-12-04T20:50:09.000Z","size":73,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-12-22T03:48:47.410Z","etag":null,"topics":["fast-api","fast-api-guide","fastapi","guide","how-to","how-to-fast-api","securing","securing-api"],"latest_commit_sha":null,"homepage":"https://github.com/VolkanSah/Securing-FastAPI-Applications","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/VolkanSah.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":["volkansah"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"lfx_crowdfunding":null,"polar":null,"buy_me_a_coffee":"volkansah","thanks_dev":null,"custom":null}},"created_at":"2025-01-12T19:40:57.000Z","updated_at":"2025-12-06T17:39:40.000Z","dependencies_parsed_at":"2025-01-12T20:27:03.752Z","dependency_job_id":"14ab1869-c4b8-4c68-b213-7f19180d812f","html_url":"https://github.com/VolkanSah/Securing-FastAPI-Applications","commit_stats":null,"previous_names":["volkansah/securing-an-api-built-with-fastapi","volkansah/securing-fastapi-applications"],"tags_count":0,"template":true,"template_full_name":null,"purl":"pkg:github/VolkanSah/Securing-FastAPI-Applications","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VolkanSah%2FSecuring-FastAPI-Applications","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VolkanSah%2FSecuring-FastAPI-Applications/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VolkanSah%2FSecuring-FastAPI-Applications/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VolkanSah%2FSecuring-FastAPI-Applications/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/VolkanSah","download_url":"https://codeload.github.com/VolkanSah/Securing-FastAPI-Applications/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/VolkanSah%2FSecuring-FastAPI-Applications/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28587034,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-19T20:45:59.482Z","status":"ssl_error","status_checked_at":"2026-01-19T20:45:41.500Z","response_time":67,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fast-api","fast-api-guide","fastapi","guide","how-to","how-to-fast-api","securing","securing-api"],"created_at":"2025-02-12T05:51:24.745Z","updated_at":"2026-01-19T22:00:57.352Z","avatar_url":"https://github.com/VolkanSah.png","language":null,"readme":"# Securing FastAPI Applications\n###### A Comprehensive Guide to Building Secure APIs with FastAPI\n\nFastAPI is a modern, high-performance web framework for building APIs with Python. While its speed and developer-friendly syntax make it an excellent choice, securing your application properly is crucial.\n\nThis guide covers key areas of API security, including authentication, input validation, HTTPS, and more. Each section includes examples and tools to help you apply best practices in real-world applications.\n\n## Table of Contents\n1. [Authentication and Authorization](#1-authentication-and-authorization)\n2. [Input Validation and Sanitization](#2-input-validation-and-sanitization)\n3. [SQL Injection Prevention](#3-sql-injection-prevention)\n4. [Password Security](#4-password-security)\n5. [CSRF Protection](#5-csrf-protection)\n6. [HTTPS (TLS/SSL)](#6-https-tlsssl)\n7. [Secure Headers](#7-secure-headers)\n8. [Rate Limiting](#8-rate-limiting)\n9. [CORS (Cross-Origin Resource Sharing)](#9-cross-origin-resource-sharing-cors)\n10. [Session Management](#10-session-management)\n11. [Secrets Management](#11-secrets-management)\n12. [Data Encryption](#12-data-encryption)\n13. [Error Handling](#13-error-handling)\n14. [File Upload Security](#14-file-upload-security)\n15. [Database Security](#15-database-security)\n16. [Logging and Monitoring](#16-logging-and-monitoring)\n17. [Static File Handling](#17-static-file-handling)\n18. [Dependency Injection](#18-dependency-injection)\n19. [Dependency Management](#19-dependency-management)\n20. [Security Best Practices](#20-security-best-practices)\n21. [Advanced Protections](#21-advanced-protections)\n22. [Checklist for Deployment](#checklist-for-deployment)\n\n---\n\n### 1. **Authentication and Authorization**\n- **Authentication**: Ensure users can securely authenticate. Use libraries like `OAuth2`, `JWT` (JSON Web Tokens), or API keys.\n    - FastAPI has built-in support for OAuth2 and JWT integration.\n    - Use `fastapi.security` to define OAuth2 token flow.\n- **Authorization**: Control access to resources based on user roles or permissions.\n    - Use dependency injection to enforce access rules at the endpoint level.\n\n**Example with proper JWT validation**:\n```python\nfrom fastapi import Depends, FastAPI, HTTPException, status\nfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm\nfrom jose import JWTError, jwt\nfrom passlib.context import CryptContext\nfrom datetime import datetime, timedelta\n\napp = FastAPI()\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\n\nSECRET_KEY = \"your-secret-key-keep-it-secret\"\nALGORITHM = \"HS256\"\nACCESS_TOKEN_EXPIRE_MINUTES = 30\n\npwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\")\n\ndef create_access_token(data: dict, expires_delta: timedelta = None):\n    to_encode = data.copy()\n    if expires_delta:\n        expire = datetime.utcnow() + expires_delta\n    else:\n        expire = datetime.utcnow() + timedelta(minutes=15)\n    to_encode.update({\"exp\": expire})\n    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)\n    return encoded_jwt\n\ndef get_current_user(token: str = Depends(oauth2_scheme)):\n    credentials_exception = HTTPException(\n        status_code=status.HTTP_401_UNAUTHORIZED,\n        detail=\"Could not validate credentials\",\n        headers={\"WWW-Authenticate\": \"Bearer\"},\n    )\n    try:\n        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])\n        username: str = payload.get(\"sub\")\n        if username is None:\n            raise credentials_exception\n    except JWTError:\n        raise credentials_exception\n    return {\"username\": username}\n\n@app.post(\"/token\")\nasync def login(form_data: OAuth2PasswordRequestForm = Depends()):\n    # Verify user credentials here\n    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)\n    access_token = create_access_token(\n        data={\"sub\": form_data.username}, expires_delta=access_token_expires\n    )\n    return {\"access_token\": access_token, \"token_type\": \"bearer\"}\n\n@app.get(\"/secure-endpoint\")\ndef secure_endpoint(user: dict = Depends(get_current_user)):\n    return {\"message\": f\"Hello, {user['username']}!\"}\n```\n\n---\n\n### 2. **Input Validation and Sanitization**\n- Validate all inputs using Pydantic models to prevent injection attacks and ensure data consistency.\n- Use field validators for additional security checks.\n\n**Example of a Pydantic model with validation**:\n```python\nfrom pydantic import BaseModel, Field, validator\nimport re\n\nclass UserInput(BaseModel):\n    username: str = Field(..., min_length=3, max_length=50)\n    email: str\n    age: int = Field(..., ge=0, le=150)\n    \n    @validator('username')\n    def username_alphanumeric(cls, v):\n        if not re.match(\"^[a-zA-Z0-9_]+$\", v):\n            raise ValueError('Username must be alphanumeric')\n        return v\n    \n    @validator('email')\n    def email_valid(cls, v):\n        if not re.match(r\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\", v):\n            raise ValueError('Invalid email format')\n        return v\n```\n\n---\n\n### 3. **SQL Injection Prevention**\n- Always use ORM (Object-Relational Mapping) like SQLAlchemy with parameterized queries.\n- Never concatenate user input directly into SQL queries.\n\n**Example with SQLAlchemy**:\n```python\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import select\n\n# GOOD - Parameterized query\ndef get_user_safe(db: Session, username: str):\n    return db.query(User).filter(User.username == username).first()\n\n# BAD - Never do this!\n# query = f\"SELECT * FROM users WHERE username = '{username}'\"\n```\n\n---\n\n### 4. **Password Security**\n- Never store passwords in plain text.\n- Use strong hashing algorithms like `bcrypt` or `argon2`.\n\n**Example**:\n```python\nfrom passlib.context import CryptContext\n\npwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\")\n\ndef hash_password(password: str) -\u003e str:\n    return pwd_context.hash(password)\n\ndef verify_password(plain_password: str, hashed_password: str) -\u003e bool:\n    return pwd_context.verify(plain_password, hashed_password)\n```\n\n---\n\n### 5. **CSRF Protection**\n- Implement CSRF tokens for state-changing operations.\n- Use the `fastapi-csrf-protect` library.\n\n**Example**:\n```python\nfrom fastapi_csrf_protect import CsrfProtect\nfrom pydantic import BaseModel\n\nclass CsrfSettings(BaseModel):\n    secret_key: str = \"your-secret-key\"\n\n@CsrfProtect.load_config\ndef get_csrf_config():\n    return CsrfSettings()\n\n@app.post(\"/form-submit\")\nasync def submit_form(csrf_protect: CsrfProtect = Depends()):\n    await csrf_protect.validate_csrf_in_cookies(request)\n    return {\"message\": \"Form submitted successfully\"}\n```\n\n---\n\n### 6. **HTTPS (TLS/SSL)**\n- Always serve your API over HTTPS to encrypt data in transit.\n- Use tools like Let's Encrypt for free TLS certificates.\n- Configure your web server (e.g., Nginx or Uvicorn) to redirect HTTP to HTTPS.\n\n**Nginx configuration example**:\n```nginx\nserver {\n    listen 80;\n    server_name yourdomain.com;\n    return 301 https://$server_name$request_uri;\n}\n\nserver {\n    listen 443 ssl http2;\n    server_name yourdomain.com;\n    \n    ssl_certificate /path/to/cert.pem;\n    ssl_certificate_key /path/to/key.pem;\n    \n    location / {\n        proxy_pass http://127.0.0.1:8000;\n    }\n}\n```\n\n---\n\n### 7. **Secure Headers**\n- Use security headers to protect your API from common attacks like XSS, clickjacking, etc.\n- Implement Content Security Policy (CSP).\n\n**Example**:\n```python\nfrom fastapi.middleware.trustedhost import TrustedHostMiddleware\nfrom fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware\nfrom starlette.middleware.base import BaseHTTPMiddleware\n\nclass SecurityHeadersMiddleware(BaseHTTPMiddleware):\n    async def dispatch(self, request, call_next):\n        response = await call_next(request)\n        response.headers['X-Content-Type-Options'] = 'nosniff'\n        response.headers['X-Frame-Options'] = 'DENY'\n        response.headers['X-XSS-Protection'] = '1; mode=block'\n        response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'\n        response.headers['Content-Security-Policy'] = \"default-src 'self'\"\n        return response\n\napp.add_middleware(SecurityHeadersMiddleware)\napp.add_middleware(TrustedHostMiddleware, allowed_hosts=[\"yourdomain.com\", \"*.yourdomain.com\"])\napp.add_middleware(HTTPSRedirectMiddleware)\n```\n\n---\n\n### 8. **Rate Limiting**\n- Implement rate limiting to prevent abuse or brute-force attacks.\n- Use tools like `slowapi`:\n\n```bash\npip install slowapi\n```\n\n```python\nfrom slowapi import Limiter, _rate_limit_exceeded_handler\nfrom slowapi.util import get_remote_address\nfrom slowapi.errors import RateLimitExceeded\nfrom fastapi import FastAPI, Request\n\nlimiter = Limiter(key_func=get_remote_address)\napp = FastAPI()\napp.state.limiter = limiter\napp.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)\n\n@app.get(\"/\")\n@limiter.limit(\"5/minute\")\nasync def home(request: Request):\n    return {\"message\": \"Welcome!\"}\n```\n\n---\n\n### 9. **Cross-Origin Resource Sharing (CORS)**\n- Restrict which domains can interact with your API.\n- Only allow trusted origins in production.\n\n```python\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp.add_middleware(\n    CORSMiddleware,\n    allow_origins=[\"https://yourdomain.com\"],  # Don't use [\"*\"] in production!\n    allow_credentials=True,\n    allow_methods=[\"GET\", \"POST\", \"PUT\", \"DELETE\"],\n    allow_headers=[\"Authorization\", \"Content-Type\"],\n    max_age=3600,\n)\n```\n\n---\n\n### 10. **Session Management**\n- Implement proper session timeout and token expiration.\n- Use secure session storage (Redis, database).\n- Implement token refresh mechanism.\n\n**Example**:\n```python\nfrom datetime import datetime, timedelta\n\nACCESS_TOKEN_EXPIRE_MINUTES = 30\nREFRESH_TOKEN_EXPIRE_DAYS = 7\n\ndef create_tokens(user_id: str):\n    access_token = create_access_token(\n        data={\"sub\": user_id},\n        expires_delta=timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)\n    )\n    refresh_token = create_access_token(\n        data={\"sub\": user_id, \"type\": \"refresh\"},\n        expires_delta=timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)\n    )\n    return {\"access_token\": access_token, \"refresh_token\": refresh_token}\n```\n\n---\n\n### 11. **Secrets Management**\n- Never hardcode secrets in your code.\n- Use environment variables with `.env` files (development only).\n- Use proper secret management in production (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault).\n- Implement secret rotation.\n\n**Example with python-dotenv**:\n```python\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv()\n\nDATABASE_URL = os.getenv(\"DATABASE_URL\")\nSECRET_KEY = os.getenv(\"SECRET_KEY\")\nAPI_KEY = os.getenv(\"API_KEY\")\n```\n\n**`.gitignore` must include**:\n```\n.env\n.env.local\n.env.*.local\nsecrets/\n*.key\n*.pem\n```\n\n---\n\n### 12. **Data Encryption**\n- Encrypt sensitive data at rest using libraries like `cryptography`.\n- Encrypt data in transit with HTTPS/TLS.\n\n**Example**:\n```python\nfrom cryptography.fernet import Fernet\n\ndef generate_key():\n    return Fernet.generate_key()\n\ndef encrypt_data(data: str, key: bytes) -\u003e bytes:\n    f = Fernet(key)\n    return f.encrypt(data.encode())\n\ndef decrypt_data(encrypted_data: bytes, key: bytes) -\u003e str:\n    f = Fernet(key)\n    return f.decrypt(encrypted_data).decode()\n```\n\n---\n\n### 13. **Error Handling**\n- Never expose sensitive information in error messages.\n- Don't show stack traces in production.\n- Use generic error messages for users.\n\n**Example**:\n```python\nfrom fastapi import FastAPI, Request, status\nfrom fastapi.responses import JSONResponse\nfrom fastapi.exceptions import RequestValidationError\n\napp = FastAPI()\n\n@app.exception_handler(RequestValidationError)\nasync def validation_exception_handler(request: Request, exc: RequestValidationError):\n    # Log the detailed error internally\n    print(f\"Validation error: {exc}\")\n    # Return generic message to user\n    return JSONResponse(\n        status_code=status.HTTP_400_BAD_REQUEST,\n        content={\"detail\": \"Invalid input data\"}\n    )\n\n@app.exception_handler(Exception)\nasync def general_exception_handler(request: Request, exc: Exception):\n    # Log the error\n    print(f\"Internal error: {exc}\")\n    # Don't expose internal details\n    return JSONResponse(\n        status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,\n        content={\"detail\": \"Internal server error\"}\n    )\n```\n\n---\n\n### 14. **File Upload Security**\n- Validate file types and sizes.\n- Scan uploaded files for malware.\n- Store files outside the web root.\n- Use unique filenames to prevent overwrites.\n\n**Example**:\n```python\nfrom fastapi import UploadFile, File, HTTPException\nimport magic\nimport uuid\nfrom pathlib import Path\n\nALLOWED_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.pdf'}\nMAX_FILE_SIZE = 5 * 1024 * 1024  # 5MB\n\n@app.post(\"/upload\")\nasync def upload_file(file: UploadFile = File(...)):\n    # Check file size\n    contents = await file.read()\n    if len(contents) \u003e MAX_FILE_SIZE:\n        raise HTTPException(status_code=400, detail=\"File too large\")\n    \n    # Check file type\n    file_ext = Path(file.filename).suffix.lower()\n    if file_ext not in ALLOWED_EXTENSIONS:\n        raise HTTPException(status_code=400, detail=\"File type not allowed\")\n    \n    # Verify MIME type\n    mime = magic.from_buffer(contents, mime=True)\n    if not mime.startswith('image/') and mime != 'application/pdf':\n        raise HTTPException(status_code=400, detail=\"Invalid file content\")\n    \n    # Save with unique filename\n    unique_filename = f\"{uuid.uuid4()}{file_ext}\"\n    file_path = Path(\"uploads\") / unique_filename\n    \n    with open(file_path, \"wb\") as f:\n        f.write(contents)\n    \n    return {\"filename\": unique_filename}\n```\n\n---\n\n### 15. **Database Security**\n- Use encrypted connection strings.\n- Apply principle of least privilege for database users.\n- Implement connection pooling with limits.\n- Regular database backups with encryption.\n\n**Example with SQLAlchemy**:\n```python\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.pool import QueuePool\n\nDATABASE_URL = \"postgresql://user:password@localhost/dbname?sslmode=require\"\n\nengine = create_engine(\n    DATABASE_URL,\n    poolclass=QueuePool,\n    pool_size=5,\n    max_overflow=10,\n    pool_pre_ping=True,  # Verify connections before using\n    echo=False  # Don't log SQL in production\n)\n```\n\n---\n\n### 16. **Logging and Monitoring**\n- Log security events (failed logins, suspicious activities).\n- Never log sensitive data (passwords, tokens, credit cards).\n- Use structured logging.\n- Implement monitoring and alerting.\n\n**Example**:\n```python\nimport logging\nfrom pythonjsonlogger import jsonlogger\n\nlogger = logging.getLogger()\n\nlogHandler = logging.StreamHandler()\nformatter = jsonlogger.JsonFormatter()\nlogHandler.setFormatter(formatter)\nlogger.addHandler(logHandler)\n\n@app.middleware(\"http\")\nasync def log_requests(request: Request, call_next):\n    logger.info(\"request_started\", extra={\n        \"method\": request.method,\n        \"path\": request.url.path,\n        \"ip\": request.client.host\n    })\n    response = await call_next(request)\n    logger.info(\"request_completed\", extra={\n        \"status_code\": response.status_code\n    })\n    return response\n```\n\n**Tools**:\n- Error tracking: Sentry, Rollbar\n- Monitoring: Prometheus, Grafana, Datadog\n- Logging: ELK Stack, Splunk\n\n---\n\n### 17. **Static File Handling**\n- Be cautious when serving static files.\n- Never expose sensitive files (.env, .git, config files).\n- Set proper permissions and access controls.\n\n**Example**:\n```python\nfrom fastapi.staticfiles import StaticFiles\nimport os\n\n# Ensure directory exists and has proper permissions\nstatic_dir = \"static\"\nif not os.path.exists(static_dir):\n    os.makedirs(static_dir, mode=0o755)\n\napp.mount(\"/static\", StaticFiles(directory=static_dir), name=\"static\")\n```\n\n---\n\n### 18. **Dependency Injection**\n- Use FastAPI's dependency injection for security checks.\n- Create reusable security dependencies.\n\n**Example**:\n```python\nfrom fastapi import Depends, HTTPException\n\ndef verify_api_key(api_key: str = Header(...)):\n    if api_key != \"expected-api-key\":\n        raise HTTPException(status_code=403, detail=\"Invalid API Key\")\n    return api_key\n\ndef check_admin_role(user: dict = Depends(get_current_user)):\n    if user.get(\"role\") != \"admin\":\n        raise HTTPException(status_code=403, detail=\"Admin access required\")\n    return user\n\n@app.delete(\"/admin/users/{user_id}\")\ndef delete_user(user_id: int, admin: dict = Depends(check_admin_role)):\n    # Only admins can access this endpoint\n    return {\"message\": f\"User {user_id} deleted by {admin['username']}\"}\n```\n\n---\n\n### 19. **Dependency Management**\n- Keep all dependencies up to date.\n- Regularly scan for vulnerabilities.\n- Use dependency pinning in production.\n\n**Tools**:\n```bash\n# Install security scanning tools\npip install pip-audit safety bandit\n\n# Run security scans\npip-audit\nsafety check\nbandit -r app/\n\n# Use requirements.txt with pinned versions\npip freeze \u003e requirements.txt\n```\n\n**GitHub Dependabot configuration** (`.github/dependabot.yml`):\n```yaml\nversion: 2\nupdates:\n  - package-ecosystem: \"pip\"\n    directory: \"/\"\n    schedule:\n      interval: \"weekly\"\n    open-pull-requests-limit: 10\n```\n\n---\n\n### 20. **Security Best Practices**\n- Follow the principle of least privilege.\n- Implement defense in depth (multiple security layers).\n- Regular security audits and penetration testing.\n- Keep FastAPI and all dependencies updated.\n- Use security linters and static analysis tools.\n- Document security policies and procedures.\n\n**Additional Security Measures**:\n- API versioning for backward compatibility\n- Protection against XXE (XML External Entity) attacks\n- SSRF (Server-Side Request Forgery) prevention\n- WebSocket security (if applicable)\n\n---\n\n### 21. **Advanced Protections**\n- Implement Web Application Firewall (WAF) rules.\n- Consider API gateways like Kong, AWS API Gateway, or Azure API Management.\n- Use DDoS protection services.\n- Implement intrusion detection systems (IDS).\n\n**Example WAF rules with ModSecurity**:\n```\n# Block common SQL injection patterns\nSecRule ARGS \"@rx (union.*select|insert.*into)\" \"id:1,deny,status:403\"\n\n# Block XSS attempts\nSecRule ARGS \"@rx (\u003cscript|javascript:)\" \"id:2,deny,status:403\"\n```\n\n---\n\n## Checklist for Deployment\n\nBefore you deploy your FastAPI application to production, make sure you've checked the following boxes:\n\n### 🔐 **Security**\n\n- [ ] **Authentication implemented** (OAuth2 / JWT / API Keys)\n- [ ] **Authorization rules enforced** (role-based / permissions)\n- [ ] **Password hashing active** (bcrypt / argon2)\n- [ ] **JWT token validation implemented** (not just mock checks)\n- [ ] **Token expiration and refresh configured**\n- [ ] **Session management secure** (timeout, secure storage)\n- [ ] **Rate limiting active** (`slowapi` or via reverse proxy)\n- [ ] **CORS configured properly** (only allow trusted domains, no `*` in production)\n- [ ] **CSRF protection enabled** for state-changing operations\n- [ ] **Security headers enabled** (CSP, X-Frame-Options, X-Content-Type-Options, etc.)\n- [ ] **HTTPS/TLS enabled** (via Nginx, Caddy, or cloud provider)\n- [ ] **HTTP to HTTPS redirect configured**\n- [ ] **Input validation implemented** (Pydantic models with validators)\n- [ ] **SQL injection prevention** (ORM usage, parameterized queries)\n- [ ] **XSS protection in place**\n- [ ] **Static file permissions checked** (no `.env` or secrets exposed)\n- [ ] **File upload security** (type validation, size limits, virus scanning)\n- [ ] **API versioning implemented**\n\n### 🔑 **Secrets \u0026 Configuration**\n\n- [ ] **No hardcoded secrets in code**\n- [ ] **Environment variables protected** (`.env` for dev, proper secrets manager for prod)\n- [ ] **`.gitignore` includes all sensitive files** (`.env`, `*.key`, `*.pem`, etc.)\n- [ ] **Secret rotation strategy defined**\n- [ ] **Database credentials encrypted**\n- [ ] **API keys stored securely**\n\n### 🛡️ **Code \u0026 Dependency Safety**\n\n- [ ] **All packages up-to-date**\n- [ ] **Security scan run** (`bandit`, `pip-audit`, `safety`)\n- [ ] **Dependencies pinned** in `requirements.txt`\n- [ ] **Dependabot or Renovate configured**\n- [ ] **No known vulnerabilities in dependencies**\n- [ ] **Remove debug endpoints or dev routes**\n- [ ] **Debug mode disabled** (`debug=False`)\n\n### 💾 **Database Security**\n\n- [ ] **Database connections encrypted** (SSL/TLS)\n- [ ] **Least privilege database user**\n- [ ] **Connection pooling configured with limits**\n- [ ] **Database backups automated and encrypted**\n- [ ] **Database credentials not in version control**\n\n### 🚨 **Error Handling \u0026 Logging**\n\n- [ ] **Error tracking active** (e.g., Sentry, Rollbar)\n- [ ] **Application logs enabled** (structured logging preferred)\n- [ ] **Sensitive data not logged** (passwords, tokens, PII)\n- [ ] **Generic error messages for users** (no stack traces exposed)\n- [ ] **Security events logged** (failed logins, suspicious activity)\n\n### 📊 **Monitoring \u0026 Alerts**\n\n- [ ] **Performance monitoring** (e.g., Prometheus, Grafana, Datadog)\n- [ ] **Alerts configured** for critical errors or traffic spikes\n- [ ] **Health check endpoints exist** (`/health`, `/ready`)\n- [ ] **Uptime monitoring configured**\n\n### 🚀 **Deployment Readiness**\n\n- [ ] **Dockerized or virtualized properly**\n- [ ] **Gunicorn/Uvicorn workers configured** (multiple workers for production)\n- [ ] **Reverse proxy configured** (Nginx, Caddy, Traefik)\n- [ ] **Load balancer configured** (if applicable)\n- [ ] **CI/CD pipeline tested** (GitHub Actions, GitLab CI, etc.)\n- [ ] **Deployment rollback strategy defined**\n- [ ] **Resource limits configured** (CPU, memory)\n\n### 🌐 **Infrastructure Security**\n\n- [ ] **Firewall rules configured**\n- [ ] **Only necessary ports open**\n- [ ] **WAF configured** (if applicable)\n- [ ] **DDoS protection enabled**\n- [ ] **Network segmentation implemented**\n- [ ] **Regular security patches applied to servers**\n\n### 🧪 **Testing**\n\n- [ ] **Manual test of all endpoints done**\n- [ ] **Auth flow tested end-to-end**\n- [ ] **Edge cases handled** (token expiry, invalid inputs, etc.)\n- [ ] **404/500 fallback routes implemented**\n- [ ] **Security testing performed** (OWASP Top 10)\n- [ ] **Penetration testing done** (if applicable)\n- [ ] **Load testing performed**\n\n### 📋 **Documentation \u0026 Compliance**\n\n- [ ] **API documentation generated** (OpenAPI/Swagger)\n- [ ] **Security policies documented**\n- [ ] **Incident response plan defined**\n- [ ] **GDPR/privacy compliance checked** (if applicable)\n- [ ] **Terms of service and privacy policy published**\n\n### 🔄 **Post-Deployment**\n\n- [ ] **Monitoring dashboards set up**\n- [ ] **On-call rotation defined**\n- [ ] **Backup restoration tested**\n- [ ] **Disaster recovery plan documented**\n- [ ] **Regular security audits scheduled**\n\n---\n\n📌 **Pro tip**: Save this checklist as `DEPLOYMENT.md` in your repo and tick the boxes during your review. Consider using tools like [GitHub issue templates](https://docs.github.com/en/communities/using-templates-to-encourage-useful-issues-and-pull-requests/configuring-issue-templates-for-your-repository) for deployment checklists.\n\n---\n\n## Additional Resources\n\n- [OWASP API Security Top 10](https://owasp.org/www-project-api-security/)\n- [FastAPI Security Documentation](https://fastapi.tiangolo.com/tutorial/security/)\n- [Python Security Best Practices](https://python.readthedocs.io/en/stable/library/security_warnings.html)\n- [CWE Top 25 Most Dangerous Software Weaknesses](https://cwe.mitre.org/top25/)\n\n---\n\n## Contributing\n\nContributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.\n\n---\n\n## License\n\nThis guide is released under the MIT License. See LICENSE file for details.\n\n---\n\n**If you found this guide useful, don't forget to ⭐ the repo!**\n\n###### Created by [VolkanSah](https://github.com/volkansah)\n","funding_links":["https://github.com/sponsors/volkansah","https://buymeacoffee.com/volkansah"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FVolkanSah%2FSecuring-FastAPI-Applications","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FVolkanSah%2FSecuring-FastAPI-Applications","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FVolkanSah%2FSecuring-FastAPI-Applications/lists"}