Python · Module 11 · Lesson 31 min read

Authentication (API Keys & JWT)

Proving who you are

MethodHow it worksUsed for
API keya secret string sent in a headerserver-to-server, public APIs
Bearer token / JWTa signed token after loginuser sessions in apps
OAuth 2.0"Sign in with Google" flowsthird-party access

JWT (JSON Web Token)

Three parts separated by dots: header.payload.signature.

  • The payload holds claims like sub (user id) and exp (expiry time).
  • The signature proves the token wasn't changed, but the payload is only encoded, not encrypted. Anyone can read it, so never put passwords in it.
  • Send it as Authorization: Bearer <token>.

Security rules 🔐

  • HTTPS only.
  • Secrets live in environment variables, never in code or Git.
  • Give tokens a short expiry (exp) and verify the signature and expiry on every request.
  • Store passwords only as hashes (bcrypt, argon2), never plain text.

💻 Uses third-party libraries (pip install requests PyJWT), so run it on a computer.

Example

Python
import os
from datetime import datetime, timedelta, timezone

import jwt          # pip install PyJWT
import requests

# 1) Calling an API with a key from the environment
API_KEY = os.environ.get("EXAMPLE_API_KEY", "")
resp = requests.get(
    "https://api.example.com/data",
    headers={"Authorization": f"Bearer {API_KEY}"},
    timeout=10,
)

# 2) Creating and verifying a JWT
SECRET = os.environ.get("JWT_SECRET", "dev-only-secret")

token = jwt.encode(
    {"sub": "user-42", "exp": datetime.now(timezone.utc) + timedelta(minutes=30)},
    SECRET,
    algorithm="HS256",
)
print(token)

try:
    claims = jwt.decode(token, SECRET, algorithms=["HS256"])
    print("Logged in as", claims["sub"])
except jwt.ExpiredSignatureError:
    print("Token expired — please log in again")
except jwt.InvalidTokenError:
    print("Invalid token")