🔐 Lesson 7.3: Securing Your App (API Keys, HTTPS, Auth)

 

🔐 Lesson 7.3: Securing Your App (API Keys, HTTPS, Auth)


🎯 Learning Objectives

By the end of this lesson, learners will:

  • Understand security risks of deploying AI chat systems publicly.

  • Secure API endpoints with authentication and authorization.

  • Store and manage API keys safely.

  • Enable HTTPS (SSL/TLS encryption) for all traffic.

  • Prevent common vulnerabilities like open access, CORS issues, and token leakage.


🧠 Core Concepts

🔑 What Are API Keys?

API keys are secret tokens used to authenticate a user or application. They’re essential for accessing services like OpenRouter, Hugging Face, or external APIs.

🛡️ HTTPS vs HTTP

HTTPS (secured via SSL/TLS) encrypts all communication between users and your server, preventing interception and tampering.

👮 Authentication vs Authorization

  • Authentication: Verifying a user’s identity (e.g., login).

  • Authorization: Verifying what a user is allowed to do.


🚧 Common Threats to AI Apps

  • Leaked API keys in frontend code

  • Exposed admin endpoints

  • No CORS protection (Cross-Origin Resource Sharing)

  • Unsecured HTTP traffic

  • No session/token expiration


🛠️ Step-by-Step Hardening Guide


✅ Step 1: Secure API Keys

  • Never expose API keys in frontend code

    • Use server-side environment variables or a backend proxy.

  • Store keys in .env:

    OPENROUTER_API_KEY=sk-abc123
    
  • Access in code securely (Python example):

    import os
    api_key = os.getenv("OPENROUTER_API_KEY")
    

✅ Step 2: Enable HTTPS

  • Use auto-SSL via:

    • Render: Automatic HTTPS via custom domain

    • Fly.io: SSL certs enabled by default

    • Vercel: HTTPS by default

  • For custom VPS:

    • Use Let’s Encrypt

    • Setup with Certbot:

      sudo apt install certbot
      sudo certbot certonly --standalone -d yourdomain.com
      

✅ Step 3: Add Authentication Layer (JWT)

Use JSON Web Tokens (JWT) to verify users:

Backend Auth Flow (FastAPI Example):

  1. User logs in → server returns JWT token.

  2. Token is stored in localStorage/cookie.

  3. All protected endpoints require token in header:

    Authorization: Bearer <token>
    

Token validation middleware:

from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/chat")
async def secure_chat(token: str = Depends(oauth2_scheme)):
    user = verify_token(token)

✅ Step 4: Enable CORS Protection

Set allowed domains in backend:

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://yourfrontend.com"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

✅ Step 5: Rate Limiting & Abuse Prevention

  • Use tools like FastAPI Limiter or Nginx:

limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
  • Protect GPT endpoints to avoid prompt flooding or scraping.


✅ Step 6: Secure Admin Tools

  • Hide backend dashboards behind authentication.

  • Use IP whitelisting for admin endpoints if needed.


🧪 Assignments & Practice

  • 🔐 Secure your .env file and make sure it’s not exposed.

  • 🛡️ Add JWT login & auth to your chatbot backend.

  • 🌐 Test HTTPS access using your public domain.

  • 🚫 Try calling your API from a different origin and confirm CORS blocks it.


📦 Downloads Included

  • Sample .env template

  • FastAPI Auth middleware snippet

  • SSL Setup PDF for VPS/Render/Fly.io

  • CORS & JWT configuration guide


✅ Summary Checklist

Security Feature Applied?
🔐 API Keys in .env ✅
🔐 HTTPS Enabled ✅
🔐 Auth with JWT or OAuth ✅
🔐 CORS Configured ✅
🔐 Rate Limiting Active ✅

🧠 Further Resources


 

83