API Security
Security practices and patterns for protecting API endpoints from unauthorized access, ensuring proper authentication and authorization at multiple layers of the application stack.
Core Security Principles
Per-Handler Authentication
Each API endpoint should implement independent authentication checks rather than relying solely on middleware:
// Vulnerable: Middleware-only protection
export async function POST(request: Request) {
// No auth check - relies on middleware
return await updateData();
}
// Secure: Per-handler authentication
export async function POST(request: Request) {
const session = await auth();
if (!session) return Response.json({ error: 'Unauthorized' }, { status: 401 });
return await updateData();
}
Defense-in-Depth Architecture
Multiple layers of security controls prevent single points of failure:
- Middleware: Global route protection
- Handler-level: Individual endpoint authentication
- Business Logic: Operation-specific authorization
- Data Layer: Database-level access controls
Common Vulnerabilities
Authentication Bypass
Risk: Server-side code importing handlers directly bypasses middleware Impact: Complete authentication bypass in certain execution contexts Solution: Implement authentication within each handler
Deprecated Framework Patterns
Problem: Relying on deprecated middleware patterns Risk: Framework updates removing support expose all routes Mitigation: Migrate to current framework authentication patterns
Weak Credential Management
Common issues include:
- Plaintext password storage in environment variables
- Lack of password hashing (bcrypt/argon2)
- No rate limiting or brute force protection
- Single shared credentials across users
Concurrent Operation Security
Locking Mechanisms
Long-running API operations require proper concurrency controls:
- Mutex/Semaphore: Prevent parallel execution
- Database Locking: Row-level or table-level locks
- Distributed Locks: Redis-based coordination
- Operation Queues: Sequential processing
State Protection
- Atomic Operations: Database transaction boundaries
- Idempotency: Safe retry mechanisms
- Conflict Detection: Optimistic concurrency control
Access Control Lists (ACL)
Role-Based Permissions
async function checkPermission(operation: string, user: User) {
const userRole = await getUserRole(user.id);
return hasPermission(userRole, operation);
}
export async function POST(request: Request) {
const session = await auth();
if (!session) return unauthorized();
const hasAccess = await checkPermission('admin:reseed', session.user);
if (!hasAccess) return forbidden();
return await seedMappings();
}
Operation-Level Authorization
- Admin Operations: Mapping reseeds, system configuration
- User Operations: Data viewing, basic updates
- System Operations: Automated sync, background tasks
Best Practices
Authentication Hardening
- Strong Password Requirements: Enforce complexity and length
- Multi-Factor Authentication: Additional security layers
- Session Management: Secure token handling and expiration
- Account Lockout: Protection against brute force attacks
API Endpoint Security
- Input Validation: Sanitize and validate all inputs
- Rate Limiting: Prevent abuse and DoS attacks
- CORS Configuration: Restrict cross-origin requests
- Error Handling: Avoid information disclosure in error messages
Monitoring and Alerting
- Failed Authentication Attempts: Detect brute force attacks
- Concurrent Operation Detection: Monitor for race conditions
- Privilege Escalation Attempts: Detect unauthorized access patterns
- API Usage Patterns: Identify anomalous behavior
Production Considerations
Deployment Security
- Environment Variable Protection: Secure credential storage
- Network Segmentation: Isolate API tiers
- TLS Termination: Encrypt data in transit
- Secret Rotation: Regular credential updates
Operational Security
- Audit Logging: Comprehensive operation tracking
- Incident Response: Rapid security issue resolution
- Penetration Testing: Regular security assessments
- Compliance: Meet regulatory requirements
See also
- authentication-systems
- Authorization Patterns
- concurrent-operation-management
- Production Security