๐Ÿ  VisualStudioTutor.com  ยท  Python Tutorial Home  ยท  Python Lesson 39 of 40
Lesson 39 of 40 Security Expert โฑ 35 min

Security โ€” Auth, OWASP & Secrets Management

Secure Python apps โ€” bcrypt hashing, JWT best practices, OWASP Top 10 mitigations, Azure Key Vault secrets, and dependency scanning.

Part 1: What You Will Learn

  • Hash passwords instead of storing plaintext credentials.
  • Create and verify signed JWT access tokens.
  • Read application secrets from environment variables.
  • Apply practical OWASP-style safeguards such as input validation, least privilege, secure error handling, and dependency scanning.

Part 2: Password Hashing and JWT

import os
import bcrypt
import jwt
from datetime import datetime, timedelta, timezone

JWT_SECRET = os.environ["JWT_SECRET"]
JWT_ALGORITHM = "HS256"

def hash_password(password: str) -> str:
    password_bytes = password.encode("utf-8")
    hashed = bcrypt.hashpw(password_bytes, bcrypt.gensalt())
    return hashed.decode("utf-8")

def verify_password(password: str, stored_hash: str) -> bool:
    return bcrypt.checkpw(
        password.encode("utf-8"),
        stored_hash.encode("utf-8"),
    )

def create_access_token(username: str) -> str:
    now = datetime.now(timezone.utc)

    payload = {
        "sub": username,
        "iat": now,
        "exp": now + timedelta(minutes=30),
    }

    return jwt.encode(
        payload,
        JWT_SECRET,
        algorithm=JWT_ALGORITHM,
    )

stored_hash = hash_password("Correct-Horse-Example")
print("Password valid:", verify_password(
    "Correct-Horse-Example",
    stored_hash,
))

token = create_access_token("student1")
print("Token created:", token[:30] + "...")
pip install bcrypt PyJWT
set JWT_SECRET=replace_with_a_long_random_secret

Part 3: Secrets and Input Validation

Do not place database passwords, API keys, signing secrets, or cloud credentials directly in source code. During local development, load them from environment variables or an ignored local configuration file. In production, use a managed secret store such as Azure Key Vault and grant the application only the permissions it needs.

Framework validation, such as Pydantic models in FastAPI, should reject malformed input before it reaches business logic. Database access should use parameterised queries or an ORM rather than building SQL statements by concatenating user input.

Part 4: Security Checklist

  • Hash passwords with a password-hashing algorithm; never encrypt and later decrypt user passwords.
  • Use HTTPS in production and set short-lived access-token expiry times.
  • Do not log passwords, access tokens, API keys, or full secret values.
  • Return safe error messages to clients while keeping detailed diagnostics in protected logs.
  • Run dependency and package vulnerability checks as part of CI.
  • Keep framework, runtime, and operating-system security updates current.

Part 5: Hands-On Practice

Mini project โ€” Secure Login API. Create a FastAPI endpoint that accepts a username and password, verifies a stored password hash, and returns a short-lived JWT. Add a second protected endpoint that requires a valid token. Store the signing secret outside the source code.

Part 6: Next Steps

Review your application for exposed secrets and unsafe inputs, then continue to Lesson 40 for the final production-application capstone.

๐Ÿ“˜ Want the complete guide with projects? Get the book โ†’