Back to Resources

Security Best Practices

Comprehensive guide to securing your API infrastructure based on OWASP guidelines, industry standards, and real-world breach analyses.

1. Authentication & Identity

Use Modern Authentication Standards

  • Implement OAuth 2.0 + OpenID Connect for delegated authorization
  • Use JWT (JSON Web Tokens) with short expiration times (15-60 minutes)
  • Implement refresh token rotation to prevent token theft
  • Never expose tokens in URLs or client-side storage vulnerable to XSS
# Bad: Token in URL
GET /api/users?token=eyJhbGciOiJIUzI1NiIsInR5cCI6...

# Good: Token in Authorization header
GET /api/users
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6...

Multi-Factor Authentication (MFA)

Require MFA for sensitive operations:

  • Password changes and account recovery
  • Financial transactions and data exports
  • Admin panel access and privilege escalation
  • API key generation and management

2. Authorization & Access Control

Prevent Broken Object Level Authorization (BOLA)

The #1 OWASP API vulnerability. Never trust client-provided object IDs:

# Vulnerable: Anyone can access any order
GET /api/orders/12345

# Secure: Validate ownership
def get_order(order_id, user_id):
    order = db.query(Order).filter(
        Order.id == order_id,
        Order.user_id == user_id  # <-- Ownership check
    ).first()
    if not order:
        raise Forbidden("Access denied")
    return order

Implement Least Privilege

  • Use Role-Based Access Control (RBAC) or Attribute-Based Access Control (ABAC)
  • Grant minimum permissions required for each API operation
  • Separate read/write permissions granularly
  • Implement API key scoping (e.g., read-only keys for analytics)

3. Data Protection & Encryption

Encryption in Transit

  • Enforce TLS 1.3 (or minimum TLS 1.2) for all API traffic
  • Disable weak ciphers and protocols (SSL 3.0, TLS 1.0, TLS 1.1)
  • Implement HTTP Strict Transport Security (HSTS) with long max-age
  • Use certificate pinning for mobile apps

Encryption at Rest

  • Encrypt sensitive data in database (PII, financial data, health records)
  • Use AES-256 or ChaCha20 for symmetric encryption
  • Store encryption keys in Hardware Security Modules (HSMs) or key vaults
  • Implement key rotation policies (every 90 days minimum)

Prevent Data Exposure

# Bad: Exposing sensitive fields
{
  "user": {
    "id": 123,
    "email": "user@example.com",
    "password_hash": "$2b$12$...",  // NEVER return this
    "ssn": "123-45-6789",            // Unnecessary exposure
    "internal_notes": "VIP customer" // Internal data
  }
}

# Good: Return only necessary fields
{
  "user": {
    "id": 123,
    "email": "user@example.com",
    "name": "John Doe"
  }
}

4. Input Validation & Sanitization

Validate All Input

  • Use schema validation (JSON Schema, Pydantic, Joi) for all endpoints
  • Whitelist allowed characters and patterns (never use blacklists)
  • Validate data types, formats, lengths, and ranges
  • Reject unexpected fields (prevent mass assignment vulnerabilities)
# Good: Strict validation with Pydantic
from pydantic import BaseModel, EmailStr, constr

class UserCreate(BaseModel):
    email: EmailStr
    name: constr(min_length=1, max_length=100)
    age: int = Field(ge=0, le=150)

    class Config:
        extra = "forbid"  # Reject unknown fields

Prevent Injection Attacks

  • SQL Injection: Always use parameterized queries/ORMs
  • NoSQL Injection: Validate MongoDB queries, escape special characters
  • Command Injection: Never pass user input to shell commands
  • LDAP/XPath Injection: Use prepared statements or escape properly

5. Rate Limiting & DDoS Protection

Implement Multiple Rate Limit Tiers

  • Global: 1000 requests/minute per IP
  • Per User: 100 requests/minute per authenticated user
  • Sensitive Endpoints: 5 login attempts per 15 minutes
  • Expensive Operations: 10 reports/hour, 1 export/hour

Return Proper Rate Limit Headers

HTTP/1.1 200 OK
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 87
X-RateLimit-Reset: 1640995200
Retry-After: 60

# When limit exceeded:
HTTP/1.1 429 Too Many Requests
Retry-After: 60
{
  "error": "Rate limit exceeded",
  "retry_after": 60
}

6. Monitoring, Logging & Incident Response

Security Logging Best Practices

Log these security events:

  • All authentication attempts (success and failure)
  • Authorization failures (BOLA attempts)
  • Input validation failures (potential injection attacks)
  • Rate limit violations
  • Privilege escalation attempts
  • Sensitive data access (PII, financial data)

Never Log Sensitive Data

❌ Never log:

  • Passwords (even hashed ones)
  • API keys, tokens, or session IDs
  • Credit card numbers or CVV codes
  • Social Security Numbers or government IDs
  • Health records or biometric data

Set Up Security Alerts

  • Alert on 10+ failed login attempts from same IP
  • Alert on unusual geographic access patterns
  • Alert on BOLA attempts (access to resources not owned)
  • Alert on sudden spike in 403/429 errors
  • Alert on new admin account creations

7. Dependency & Infrastructure Security

Dependency Management

  • Run npm audit or safety check in CI/CD pipeline
  • Use Dependabot, Snyk, or Renovate for automated dependency updates
  • Pin exact versions in production (avoid ^ or ~ in package.json)
  • Review and audit new dependencies before adding

Container & Infrastructure Security

  • Scan Docker images with Trivy, Snyk, or Clair
  • Use minimal base images (alpine, distroless)
  • Run containers as non-root user
  • Implement pod security policies in Kubernetes
  • Enable network policies to restrict pod-to-pod traffic

Secret Management

  • Use dedicated secret managers (Vault, AWS Secrets Manager, Azure Key Vault)
  • Never commit secrets to Git (use .gitignore, pre-commit hooks)
  • Rotate secrets every 90 days minimum
  • Use different secrets for dev/staging/production

Save These Best Practices

Download this guide for offline reference and team training

No email required • Instant download

Automate These Best Practices

G8KEPR implements all these security best practices automatically. Get enterprise-grade API security without the complexity.

API Security Resources & Blog | G8KEPR