api-security-best-practices
API Security Best Practices
Section titled “API Security Best Practices”Overview
Section titled “Overview”Guide developers in building secure APIs by implementing authentication, authorization, input validation, rate limiting, and protection against common vulnerabilities. This skill covers security patterns for REST, GraphQL, and WebSocket APIs.
When to Use This Skill
Section titled “When to Use This Skill”- Use when designing new API endpoints
- Use when securing existing APIs
- Use when implementing authentication and authorization
- Use when protecting against API attacks (injection, DDoS, etc.)
- Use when conducting API security reviews
- Use when preparing for security audits
- Use when implementing rate limiting and throttling
- Use when handling sensitive data in APIs
How It Works
Section titled “How It Works”Step 1: Authentication & Authorization
Section titled “Step 1: Authentication & Authorization”I’ll help you implement secure authentication:
- Choose authentication method (JWT, OAuth 2.0, API keys)
- Implement token-based authentication
- Set up role-based access control (RBAC)
- Secure session management
- Implement multi-factor authentication (MFA)
Step 2: Input Validation & Sanitization
Section titled “Step 2: Input Validation & Sanitization”Protect against injection attacks:
- Validate all input data
- Sanitize user inputs
- Use parameterized queries
- Implement request schema validation
- Prevent SQL injection, XSS, and command injection
Step 3: Rate Limiting & Throttling
Section titled “Step 3: Rate Limiting & Throttling”Prevent abuse and DDoS attacks:
- Implement rate limiting per user/IP
- Set up API throttling
- Configure request quotas
- Handle rate limit errors gracefully
- Monitor for suspicious activity
Step 4: Data Protection
Section titled “Step 4: Data Protection”Secure sensitive data:
- Encrypt data in transit (HTTPS/TLS)
- Encrypt sensitive data at rest
- Implement proper error handling (no data leaks)
- Sanitize error messages
- Use secure headers
Step 5: API Security Testing
Section titled “Step 5: API Security Testing”Verify security implementation:
- Test authentication and authorization
- Perform penetration testing
- Check for common vulnerabilities (OWASP API Top 10)
- Validate input handling
- Test rate limiting
Examples
Section titled “Examples”detailed code examples for JWT Authentication, SQL Injection Prevention, and Rate Limiting are available in the references:
Best Practices
Section titled “Best Practices”✅ Do This
Section titled “✅ Do This”- Use HTTPS Everywhere - Never send sensitive data over HTTP
- Implement Authentication - Require authentication for protected endpoints
- Validate All Inputs - Never trust user input
- Use Parameterized Queries - Prevent SQL injection
- Implement Rate Limiting - Protect against brute force and DDoS
- Hash Passwords - Use bcrypt with salt rounds >= 10
- Use Short-Lived Tokens - JWT access tokens should expire quickly
- Implement CORS Properly - Only allow trusted origins
- Log Security Events - Monitor for suspicious activity
- Keep Dependencies Updated - Regularly update packages
- Use Security Headers - Implement Helmet.js
- Sanitize Error Messages - Don’t leak sensitive information
❌ Don’t Do This
Section titled “❌ Don’t Do This”- Don’t Store Passwords in Plain Text - Always hash passwords
- Don’t Use Weak Secrets - Use strong, random JWT secrets
- Don’t Trust User Input - Always validate and sanitize
- Don’t Expose Stack Traces - Hide error details in production
- Don’t Use String Concatenation for SQL - Use parameterized queries
- Don’t Store Sensitive Data in JWT - JWTs are not encrypted
- Don’t Ignore Security Updates - Update dependencies regularly
- Don’t Use Default Credentials - Change all default passwords
- Don’t Disable CORS Completely - Configure it properly instead
- Don’t Log Sensitive Data - Sanitize logs
Anti-Patterns
Section titled “Anti-Patterns”Problem: JWT Secret Exposed in Code
Section titled “Problem: JWT Secret Exposed in Code”Symptoms: JWT secret hardcoded or committed to Git Solution: ```javascript // ❌ Bad const JWT_SECRET = ‘my-secret-key’;
// ✅ Good const JWT_SECRET = process.env.JWT_SECRET; if (!JWT_SECRET) { throw new Error(‘JWT_SECRET environment variable is required’); }
// Generate strong secret // node -e “console.log(require(‘crypto’).randomBytes(64).toString(‘hex’))” ```
Problem: Weak Password Requirements
Section titled “Problem: Weak Password Requirements”Symptoms: Users can set weak passwords like “password123” Solution: ```javascript const passwordSchema = z.string() .min(12, ‘Password must be at least 12 characters’) .regex(/[A-Z]/, ‘Must contain uppercase letter’) .regex(/[a-z]/, ‘Must contain lowercase letter’) .regex(/[0-9]/, ‘Must contain number’) .regex(/[^A-Za-z0-9]/, ‘Must contain special character’);
// Or use a password strength library const zxcvbn = require(‘zxcvbn’); const result = zxcvbn(password); if (result.score < 3) { return res.status(400).json({ error: ‘Password too weak’, suggestions: result.feedback.suggestions }); } ```
Problem: Missing Authorization Checks
Section titled “Problem: Missing Authorization Checks”Symptoms: Users can access resources they shouldn’t Solution: ```javascript // ❌ Bad: Only checks authentication app.delete(‘/api/posts/:id’, authenticateToken, async (req, res) => { await prisma.post.delete({ where: { id: req.params.id } }); res.json({ success: true }); });
// ✅ Good: Checks both authentication and authorization app.delete(‘/api/posts/:id’, authenticateToken, async (req, res) => { const post = await prisma.post.findUnique({ where: { id: req.params.id } });
if (!post) { return res.status(404).json({ error: ‘Post not found’ }); }
// Check if user owns the post or is admin if (post.userId !== req.user.userId && req.user.role !== ‘admin’) { return res.status(403).json({ error: ‘Not authorized to delete this post’ }); }
await prisma.post.delete({ where: { id: req.params.id } }); res.json({ success: true }); }); ```
Problem: Verbose Error Messages
Section titled “Problem: Verbose Error Messages”Symptoms: Error messages reveal system details
Solution:
```javascript
// ❌ Bad: Exposes database details
app.post(‘/api/users’, async (req, res) => {
try {
const user = await prisma.user.create({ data: req.body });
res.json(user);
} catch (error) {
res.status(500).json({ error: error.message });
// Error: “Unique constraint failed on the fields: (email)”
}
});
// ✅ Good: Generic error message app.post(‘/api/users’, async (req, res) => { try { const user = await prisma.user.create({ data: req.body }); res.json(user); } catch (error) { console.error(‘User creation error:’, error); // Log full error
if (error.code === 'P2002') { return res.status(400).json({ error: 'Email already exists' });}
res.status(500).json({ error: 'An error occurred while creating user'});} }); ```
Security Checklist
Section titled “Security Checklist”Authentication & Authorization
Section titled “Authentication & Authorization”- Implement strong authentication (JWT, OAuth 2.0)
- Use HTTPS for all endpoints
- Hash passwords with bcrypt (salt rounds >= 10)
- Implement token expiration
- Add refresh token mechanism
- Verify user authorization for each request
- Implement role-based access control (RBAC)
Input Validation
Section titled “Input Validation”- Validate all user inputs
- Use parameterized queries or ORM
- Sanitize HTML content
- Validate file uploads
- Implement request schema validation
- Use allowlists, not blocklists
Rate Limiting & DDoS Protection
Section titled “Rate Limiting & DDoS Protection”- Implement rate limiting per user/IP
- Add stricter limits for auth endpoints
- Use Redis for distributed rate limiting
- Return proper rate limit headers
- Implement request throttling
Data Protection
Section titled “Data Protection”- Use HTTPS/TLS for all traffic
- Encrypt sensitive data at rest
- Don’t store sensitive data in JWT
- Sanitize error messages
- Implement proper CORS configuration
- Use security headers (Helmet.js)
Monitoring & Logging
Section titled “Monitoring & Logging”- Log security events
- Monitor for suspicious activity
- Set up alerts for failed auth attempts
- Track API usage patterns
- Don’t log sensitive data
OWASP API Security Top 10
Section titled “OWASP API Security Top 10”- Broken Object Level Authorization - Always verify user can access resource
- Broken Authentication - Implement strong authentication mechanisms
- Broken Object Property Level Authorization - Validate which properties user can access
- Unrestricted Resource Consumption - Implement rate limiting and quotas
- Broken Function Level Authorization - Verify user role for each function
- Unrestricted Access to Sensitive Business Flows - Protect critical workflows
- Server Side Request Forgery (SSRF) - Validate and sanitize URLs
- Security Misconfiguration - Use security best practices and headers
- Improper Inventory Management - Document and secure all API endpoints
- Unsafe Consumption of APIs - Validate data from third-party APIs
Related Skills
Section titled “Related Skills”- vulnerability-scanner - Security testing perspective
- sql-injection-testing - Testing for SQL injection
- secure-refactoring - Fixing security issues
Additional Resources
Section titled “Additional Resources”- OWASP API Security Top 10
- JWT Best Practices
- Express Security Best Practices
- Node.js Security Checklist
- API Security Checklist
Pro Tip: Security is not a one-time task - regularly audit your APIs, keep dependencies updated, and stay informed about new vulnerabilities!
Gap Analysis Rule
Section titled “Gap Analysis Rule”Always identify gaps and suggest next steps to users. In case there is no gaps anymore, then AI should clearly state that there is no gap left.